Python Program to Find the Sum of Natural Numbers


In this program, you'll learn to find the sum of a natural number using while loop and display it.


In the program below, we've used an if else statement in combination with a while loop to calculate the sum of natural upto num.

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

# change this value for a different result
num = 16

# uncomment to 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

The sum is 136


Note : To test the program , change the value of num.

Here, we store the number in num 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 program without using any loop using any loops using any loops using a formula directly.

Your turn : Modify the above program to find the sum of natural numbers using the formula below.
n*(n+1)/2

For example, if n = 16, the sum would be (16 * 17)/2 = 136.