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)
Hint:
Approach 1: Use
for
loop andrange()
functions = 0
to store the sum of all numbersinput()
to take input from a userint()
constructor and save it to variablen
n
times using for loop and range() functioni
) to variables
print()
function to display the variables
on screenApproach 2: Use the built-in function sum(). The sum() function calculates the addition of numbers in the list or range
Solution1:Using
for
loop andrange()
functionSolution2:Using the built-in function
need an explanation for this answer? contact us directly to get an explanation for this answersum()