Python Program to Find the Sum of Natural Numbers

In this example, we will write a simple program to take input number from the user and calculate the sum of the natural numbers. To better understand this example, make sure you have knowledge of the following tutorials:-

A natural number is an integer greater than 0. Natural numbers begin at 1 and increment to infinity: 1, 2, 3, 4, 5, etc.

Python Program to Find the Sum of Natural Numbers

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

if number < 0:
print("Enter a positive number")
else:
sum = 0
while(number > 0):
sum += number
number -= 1
print("The sum is",sum)

The output of the above program is:-

Enter a number: 5
The sum is 15

Program Explanation

The user provides the number up to which the sum needs to be generated.  The sum is initialized as 0 and while loop is used to update the sum with the addition of the number in each loop. The loop is maintained until the number is greater than 0 and finally, the sum is printed.

Python Program to Find the Sum of Natural Numbers using a mathematical formula

THe formula n*(n+1)/2 can be used to calculate the sum directly.
number = int(input("Enter a number: "))
sum = number * (number + 1) / 2
print("The sum is: ", sum)

The output of the above program is:-

Enter a number: 5
The sum is 15