Find the Sum of Natural Numbers

In this Python lesson, we will practice how to write a program that finds the sum of natural numbers. Natural numbers are known as positive integers such as 1, 2, 3, 4, 5 … nth and so on. Let us learn how to find the sum of the natural numbers below from 1 to the given nth number.

Example 1: Get the Sum of Natural Numbers Using while Loop

# request input from user
num = int(input('Enter nth number: '))

if num < 0:
   print('Enter only positive number')
else:
   sum = 0
   # use while loop to iterate until zero
   while(num > 0):
       sum += num
       num -= 1
   print('Sum = {0}'.format(sum))

Output

Enter nth number: 8
Sum = 36

In the program above, we prompted the user to enter only positive numbers so that we can find the sum of the natural numbers.

We used the while loop to obtain the sum of natural numbers during iteration.

  • The program ensures that the while loop continues until the number is less than or equal to 8.
  • During each iteration, x is added to the sum variable which we created and the value of x is increased by 1 at each iteration period. 
  • If x becomes 9, the test condition becomes false and the sum will be equal to 0 + 1 + 2 + … + 8.

Another way of solving the program is by using the following formula.

n*(n+1)/2

For example, if n = 10, the sum would be (10*11)/2 = 55.

Example 2: Get the Sum of Natural Numbers Using n(n+1)/2

# request input from user
num = int(input('Enter nth number: '))

if num >= 0:
   sum = num*(num+1)/2
   print('Sum = {0}'.format(sum))
else:
    print('Enter only positive number')

Output

Enter nth number: 8
Sum = 36

Do you want to become an expert programmer? See books helping our students, interns, and beginners in software companies today (Click here)!

Leave a Comment

Python Tutorials