Python Program to find Sum of N Natural Numbers

Python program to find sum of n natural numbers; Through this tutorial, i am going to show you how to find the sum of the first n natural number using while loop, for loop, and recursion function.

Formula for Find or Calculate Sum of N Natural Numbers = [n(n+1)]/2 .

Python Programs to Find/Calculate Sum Of n Natural Numbers

There are three different ways to find sum of n natural numbers in python; as shown below:

  • Python Program to Calculate Sum of N Natural Numbers using While Loop
  • Python Program to find Sum of N Natural Numbers using For Loop
  • Python Program to calculate Sum of N Natural Numbers using Recursion Function

Python Program to Calculate Sum of N Natural Numbers using While Loop

  • Get input number from the user in program
  • Iterate while loop and calculate sum of n natural number
  • As well as store value in variable
  • Print sum of n natural number
# Python Program to find Sum of N Natural Numbers
 
number = int(input("Please Enter any Number: "))
total = 0
value = 1
while (value <= number):
    total = total + value
    value = value + 1
print("The Sum of Natural Numbers from 1 to {0} =  {1}".format(number, total))

Output

Please Enter any Number: 5
The Sum of Natural Numbers from 1 to 5 =  15

Python Program to find Sum of N Natural Numbers using For Loop

  • Get input number from the user in program
  • Iterate for loop and calculate sum of n natural number
  • As well as store value in variable
  • Print sum of n natural number
# Python Program to find Sum of N Natural Numbers
 
number = int(input("Please Enter any Number: "))
total = 0
for value in range(1, number + 1):
    total = total + value
print("The Sum of Natural Numbers from 1 to {0} =  {1}".format(number, total))

Output

Please Enter any Number: 10
The Sum of Natural Numbers from 1 to 10 =  55

Python Program to calculate Sum of N Natural Numbers using Recursion Functions

  • Get input number from the user in program
  • Define a function, which is calcuate sum of n natural number
  • As well as store value in variable
  • Print sum of n natural number
# Python Program to find Sum of N Natural Numbers
 
def sum_of_n_natural_numbers(num):
    if(num == 0):
        return num
    else:
        return (num + sum_of_n_natural_numbers(num - 1))
    
number = int(input("Please Enter any Number: "))
total_value = sum_of_n_natural_numbers(number)
print("Sum of Natural Numbers from 1 to {0} =  {1}".format(number, total_value))

Output

Please Enter any Number: 10
The Sum of Natural Numbers from 1 to 10 =  55

Recommended Python Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published.