# 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

3. You can use a for loop to iterate from 1 to N.
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: "))

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

Python Program using While Loop

``````import sys

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

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

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 will be float because of divide opeartion

#cast to int

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

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: