Sum of First N Natural Numbers - Python Program
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
Example: If N = 6, sum of first 6 Natural Numbers is calculated as below.
1 + 2 + 3 + 4 + 5 + 6
= 21
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
- Take an integer in
n
. - answer = 0
- You can use a for loop to iterate from
1
ton
.- In the for loop, add the number to answer.
- After you come out of the loop, you have the sum of first
n
natural numbers in your answer.
Python Program using For loop
n = 10
answer = 0
for i in range(0, n+1):
answer += i;
print(answer)
Python Program using While loop
n = 10
answer = 0
i = 1
while i <= N:
answer += i
i += 1
print(answer)
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
We will use this formula and write a python program to compute the answer.
Python Program using formula
n = 20
answer = (n * (n + 1)) / 2
answer = int(answer)
print(answer)
Output
210
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
#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.