Q:

Write a python program to accept a number from a user and calculate the sum of all numbers from 1 to a given number

belongs to collection: Python Loop Exercises

0

Calculate the sum of all numbers from 1 to a given number

Write a program to accept a number from a user and calculate the sum of all numbers from 1 to a given number

For example, if the user entered 10 the output should be 55 (1+2+3+4+5+6+7+8+9+10)

Expected Output:

Enter number 10
Sum is:  55

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Hint:

Approach 1: Use for loop and range() function

  • Create variable s = 0 to store the sum of all numbers
  • Use Python 3’s built-in function input() to take input from a user
  • Convert user input to the integer type using the int() constructor and save it to variable n
  • Run loop n times using for loop and range() function
  • In each iteration of a loop, add current number (i) to variable s
  • Use the print() function to display the variable s on screen

Approach 2: Use the built-in function sum(). The sum() function calculates the addition of numbers in the list or range

Solution1:Using for loop and range() function

# s: store sum of all numbers
s = 0
n = int(input("Enter number "))
# run loop n times
# stop: n+1 (because range never include stop number in result)
for i in range(1, n + 1, 1):
    # add current number to sum variable
    s += i
print("\n")
print("Sum is: ", s)

Solution2:Using the built-in function sum()

n = int(input("Enter number "))
# pass range of numbers to sum() function
x = sum(range(1, n + 1))
print('Sum is:', x)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Display numbers from a list using loop using pytho... >>
<< Write a python program to print the following numb...