In this post, we will learn how to find the sum of natural numbers in Python using for loop, while loop, and function with detailed explanations and examples.
But before we jump into the programming part first let’s understand what are natural numbers.
What are Natural Numbers?
The natural numbers are collection of positive numbers starting from 1 to ∞
For Example 1,2,3,4,5,6,7,8,9… etc are natural numbers
Algorithm
- Take input from the user (
num
). - take one variable
total
to store the sum of all the natural numbers, initially set to zero (total = 0
). - Using for-loop iterate from 1 to num (
for i in range(1, num+1)
). - Inside for-loop do
total+=i
- At the end outside of the loop print
total
.
Now, based on the above explanation, we understand what natural numbers are and how to implement a program to calculate their sum in Python. So, let’s now dive into the programming part.
Sum of natural numbers in Python Using for loop
Few programming concepts you have to know before writing this program:
Source Code
num = int(input("Enter a number: "))
total = 0
for i in range(1,num+1):
total+=i
print(f"Sum of 1 to {num} natural numbers is : {total}")
Output
Enter a number: 10
Sum of 1 to 10 natural numbers is : 55
Sum of natural numbers in Python Using while loop
Before writing this program few programming concepts you have to know:
NOTE: For this program, the above algorithm is being used, only the syntax has been changed.
Source Code
num = int(input("Enter a number: "))
total = 0
i = 0
while i<=num:
total+=i
i = i+1
print(f"Sum of 1 to {num} natural numbers is : {total}")
Output
Enter a number: 20
Sum of 1 to 20 natural numbers is : 210
Sum of natural numbers in Python Using function
Before writing this program few programming concepts you have to know:
Source Code
def sum_n(n):
total = 0
for i in range(1, n+1):
total+=i
return total
num = int(input("Enter a number: "))
print(f"Sum of 1 to {num} natural numbers is : {sum_n(num)}")
Output
Enter a number: 5
Sum of 1 to 5 natural numbers is : 15