Python program to find sum of ‘n’ natural numbers
In this tutorial, we will learn to find the sum of the first ‘n’ natural numbers in Python. Many times, we need to solve series which contains natural numbers sequentially. So, we can easily calculate the sum of all the terms of the series using a Python program. Here, we will learn about the natural numbers, a method to find the sum using a Python program.
Calculate the sum of ‘n’ natural numbers
Firstly, natural numbers range from 1 to infinity. So, to calculate the sum of first ‘n’ natural numbers, follow the following steps-
- Firstly, declare a loop control variable say ‘num’ and variable ‘terms_sum’ to store the result.
- Initialize the loop control variable with value 1 and the variable ‘terms_sum’ with 0.
- If the value of ‘num’ is less than or equal to ‘n’, add value in ‘num’ to ‘terms_sum’.
- Repeat the above step until the condition is true.
- Finally, display the value stored in ‘terms_sum’.
For example –
Let us assume n = 14. So we the sum of the first 14 natural numbers is – 105
For the repetition of the step, we will use a ‘for’ loop. So, the for loop in Python is as follows-
terms_sum = 0 for num in range(1,terms+1): terms_sum = terms_sum + num
The ‘terms_sum’ contains the result i.e. sum.
Python program to calculate the sum of the first ‘n’ natural numbers
Now, we will see a Python program that calculates the sum of the first ‘n’ natural number. Here, we will take the value of ‘n’ from the user as an input. The Python program is given below-
terms = int(input("ENTER NUMBER OF TERMS : ")) terms_sum = 0 for num in range(1,terms+1): terms_sum = terms_sum + num print("SUM OF FIRST",terms,"NUMBERS IS :",terms_sum)
Firstly, the program takes the number of terms from the user. Then it initializes the sum with 0. The for loop calculates the sum by adding each term. Finally, the program displays the sum of the first ‘n’ natural numbers.
The output of the Python program
This program displays the total sum i.e. the required result. The output of the above Python program is-
siddharth@siddharth-Lenovo-Y520-15IKBN:~/python$ python3 sum_natural.py ENTER NUMBER OF TERMS : 10 SUM OF FIRST 10 NUMBERS IS : 55 siddharth@siddharth-Lenovo-Y520-15IKBN:~/python$
So, the sum of the first 10 natural numbers is 55.
Thank you for reading this tutorial. I hope it helps you.
Also, read: Python program to draw line using coordinates