Python – Sum of First N Natural Numbers

Find the sum of first N natural numbers with Python Program

In this tutorial, we will find the sum of first N natural numbers. We shall explain the problem statement, and explore different ways to solve this problem.

Problem Statement

Find the sum of first N natural numbers.

1 + 2 + 3 + 4 . . + N
Run this program ONLINE

Example: If N = 6, sum of first 6 Natural Numbers is calculated as below.

1 + 2 + 3 + 4 + 5 + 6
= 21
Run this program ONLINE

User will provide the N through console. So, you have to read the N from console. And you should print the sum to the console.

Solution 1

  1. Read N from User.
  2. answer = 0
  3. You can use a for loop to iterate from 1 to N.
    1. In the for loop, add the number to answer.
  4. After you come out of the loop, you have the sum of first N natural numbers in your answer.

Python Program using for Loop

import sys

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

answer=0

for i in range(0,N+1):
	answer = answer + i;

print(answer)

Python Program using While Loop

import sys

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

answer=0

i=1
while i<=N:
	answer = answer + i
	i=i+1

print(answer)

Output

Solution 2

The formula to find the sum of first N natural numbers is given below:

Sum of first N natural numbers = (N*(N+1))/2
Run this program ONLINE

We will use this formula and write a python program to compute the answer.

Python Program using formula

import sys

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

answer = (N*(N+1))/2
#answer will be float because of divide opeartion

#cast to int
answer = int(answer)

print(answer)

Output

Enter a natural number: 5
15
Run this program ONLINE

Validating input from User

In all the above programs, we have not considered the case where user could provide an incorrect input.

Let us validate the input to be a natural number. For that, we should check if the given input is a number and then if it is greater than zero.

Python Program with input validation

import sys

#read the input
N = input("Enter a natural number: ")

#assume everything is fine
validation = True

#if N is not numeric, validation fails
if not(N.isnumeric()):
	validation = False
else:
	N=int(N)
	#if n is less than 1, it is not a natural number
	if (N<1):
		validation = False

if validation:
	answer = (N*(N+1))/2
	answer = int(answer)
	print(answer)
else:
	print('Input is not a natural number. Try again.')

These validation cases are only for demonstration purpose. You may think of some more validations and incorporate in the Python program.

Summary

In this tutorial of Python Examples, we learned different ways of writing Python program to find the sum of first N natural numbers.