Exercise 4:
Sum of Numbers from 1 to n in Python
Write a program in Python which receives the natural number n as input and then calculates and prints the sum of the natural numbers from 1 to n.
Code:
n = int(input("n = "))
s = 0
for i in range(1,n+1):
s += i
print("s = ", s)
Run:
=============== RESTART: C:\The Sum of 1 to n.py ==============
n = 5
s = 15
>>>
=============== RESTART: C:\The Sum of 1 to n.py ==============
n = 100
s = 5050
>>>
=============== RESTART: C:\The Sum of 1 to n.py ==============
n = 167
s = 14028
>>>
=============== RESTART: C:\The Sum of 1 to n.py ==============
n = 1000
s = 500500