Computer Science, asked by iamros226, 2 months ago

accept number from user and calculatr the sum of all from 1 to a given number do program in python

Answers

Answered by Anonymous
8

Sum of numbers - Python

What we need to do

We would take a user float input first, to accept the number from user. We know that when we want the user to type in a decimal value, we use float(input()) function.

After this, we know that the formula of sum of numbers, so we will use sum of numbers formula. We know the first term is 1 in the question it is given that the first term is 1 and we also know that the last nth term is represented as n.

We then print out the sum of numbers with the answer.

Why we use float() function

We use \tt{float()} function since user can also enter the decimal value, values could always have the possibility of being in decimals. If we use \tt{int()} function as the data type and a user enters a decimal value or integers, the program would result in an error. To be on the safer side, we use \tt{float()} as both integers and decimals are accepted.

\rule{300}{1}

The Program

# Taking user input

n=float(input("Enter a number:"))

# Using sum of numbers formula, we know the first term is 1 in the question it is given that first term is 1 and we also know that the last nth term is represented as n

a=1

sum=n/2*(a+n)

# Now we can print out the sum of numbers

print("The sum of all numbers from 1 to given number is", sum)

\rule{300}{1}

Sample Run

Enter a number: 5

The sum of all numbers from 1 to given number is 15.0

Answered by BrainlyProgrammer
5

Answer:

n=(int)(input("Enter a number:"))

s=0

for I in range(n+1):

‎ ‎ ‎ ‎s+=I

print(f"Sum:{s}")

Logic:

  • Run a loop from 0 to given number
  • calculate sum
  • display sum

Note:-

  • You can also write for I in range(1,n+1) won't change you output.
  • By default, loop starts with 0.
Similar questions