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

  1. Take input from the user (num).
  2. take one variable total to store the sum of all the natural numbers, initially set to zero (total = 0).
  3. Using for-loop iterate from 1 to num (for i in range(1, num+1)).
  4. Inside for-loop do total+=i
  5. 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:

  1. How to take input from the user
  2. Operators in python
  3. for- loop

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:

  1. How to take input from the user
  2. Operators in python
  3. while- loop

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:

  1. How to take input from the user
  2. Operators in python
  3. for- loop
  4. Python Functions

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
Author

Hi, I'm Yagyavendra Tiwari, a computer engineer with a strong passion for programming. I'm excited to share my programming knowledge with everyone here and help educate others in this field.

Write A Comment