08-Oct-2022
.
Admin
Hi Dev,
This post will give you example of How to Find Sum of Natural Number in Python. if you want to see example of Python Program to find Sum of N Natural Numbers using Loop then you are a right place. Here you will learn Sum of n Natural Numbers in Python. we will help you to give example of write a program to find the sum of n natural numbers in Python. Here, Creating a basic example of Sum of n numbers using while loop in Python.
Python program to find sum of n numbers; In this tutorial, you will learn how to find or calculate sum of n numbers using for loop, while loop and function.
let's see below simple example with output:
Example 1: Find/Calculate the sum of n natural numbers using loop and range function
n = input("Enter Number to calculate sum")
n = int (n)
sum = 0
for num in range(0, n+1, 1):
sum = sum+num
print("SUM of first ", n, "numbers is: ", sum )
Output:
Enter Number to calculate sum 10
Sum of first 10 number is: 55
Example 2: Find/Calculate Sum of n natural numbers in python using while loop
Python program to find the sum of n numbers using While loop:
n = input("Enter Number to calculate sum")
n = int (n)
total_numbers = n
sum=0
while (n >= 0):
sum += n
n-=1
print ("sum using while loop ", sum)
Output:
Enter Number to calculate sum 10
Sum using while loop 55
Example 3: Python program to Find/Calculate the sum of numbers in a given list
sum = 0
list = [10,24,46,20,15,5,30]
for num in list:
sum = sum +num
print ("sum of list element is : ", sum)
Output:
sum of list element is : 150
Example 4: The mathematical formula to Find/Calculate the sum of n numbers with python program
n = input("Enter a number to calculate sum")
n = int (n)
#using this formula n * (n+1) / 2
sum = n * (n+1) / 2
print("Sum of fthe irst ", n, "natural numbers using formula is: ", sum )
Output:
Enter a number to calculate sum 7
Sum of fthe irst 7 natural numbers using formula is: 28.0
Example 5: Python Program to Find/Calculate sum of n odd natural numbers
Python program to find sum of n odd numbers:
n = input("Enter Number to calculate sum")
n = int (n)
sum = 0
for num in range(0, n+1, 1):
if(not (num % 2) == 0):
sum += num;
print("SUM of odd numbers is: ", sum )
Output:
Enter Number to calculate sum 5
SUM of odd numbers is: 9
Example 6: Python Program to Find/Calculate sum of n even natural numbers
Python program to find sum of n even numbers:
n = input("Enter Number to calculate sum")
n = int (n)
sum = 0
for num in range(0, n+1, 1):
if((num % 2) == 0):
sum += num;
print("SUM of even numbers is: ", sum )
Output:
Enter Number to calculate sum 5
SUM of even numbers is: 9
I hope it can help you...
#Python