Python Program to Find the Sum of Natural Numbers


To understand this example, you should have knowledge of following Python programming topics:

Source Code


# Python program to find the sum of natural numbers up to n where n is provided by user

# take input from the user
num = int(input("Enter a number: "))

if num < 0:
   print("Enter a positive number")
else:
   sum = 0
   # use while loop to iterate un till zero
   while(num > 0):
       sum += num
       num -= 1
   print("The sum is",sum)
Output

Enter a number: 16
The sum is 136
Here, we ask the user for a number and display the sum of natural numbers up to that number. We use while loop to iterate until the number becomes zero.
We could have solved the above problem without using any loops. From mathematics, we know that sum of natural numbers is given by n*(n+1)/2. We could have used this formula directly. For example, if n = 16, the sum would be (16*17)/2 = 136.

Comments