Write a Python Program to find Sum of N Natural Numbers using While Loop, For Loop, and Functions with an example.
Python Program to find Sum of N Natural Numbers using For Loop
This program allows users to enter any integer value. Next, it calculates the sum of natural numbers from 1 to a user-specified value using For Loop.
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))
Please Enter any Number: 25
The Sum of Natural Numbers from 1 to 25 = 325
Python Program to Calculate Sum of N Natural Numbers using While Loop
In this program, we just replaced the For Loop with While Loop.
num = int(input("Please Enter any Num: ")) total = 0 value = 1 while (value <= num): total = total + value value = value + 1 print("The Sum from 1 to {0} = {1}".format(num, total))
Please Enter any Num: 12
The Sum from 1 to 12 = 78
Python Program to find Sum of N Natural Numbers using Functions
In this program, we created a new function to find the sum of natural numbers. Inside this function, we used the If Else statement.
def sum_of_n_natural_numbers(num): if(num == 0): return num else: return (num * (num + 1) / 2) number = int(input("Please Enter any Number: ")) total_value = sum_of_n_natural_numbers(number) print("Sum from 1 to {0} = {1}".format(number, total_value))
Please Enter any Number: 100
Sum from 1 to 100 = 5050.0
Python Program to Calculate Sum of N Natural Numbers using Recursion
This sum of natural numbers program is the same as the above example, but we are using Recursion this time.
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))
