Find the Sum of Natural Numbers in Python

(Last Updated On: 20/12/2022)

Python Program to Find the Sum of Natural Numbers

# Find the Sum of Natural Numbers in python

# we are taking a number from user as input
# entered value will be converted to int from string   	 
num = int(input("Enter the number:"))

# we have used an if...else statement in a combination with a while loop to calculate the sum of natural numbers up to num
if num < 0:
   print("Enter a positive number")
else:
   sum = 0
   # use while loop to iterate until zero
   while(num > 0):
   	sum += num
   	num -= 1
   print("The sum is", sum)

Output:

Enter the number:123
The sum is 7626

Leave a Reply

Your email address will not be published. Required fields are marked *