In this tutorial, we will write a simple Python program to calculate the sum of first n natural numbers.
Program to calculate sum of first n natural numbers in Python
In this program we are not using the natural number addition formula n(n+1)/2, instead we are adding the natural numbers using while loop. The user is asked to enter the value of n and then the program calculates the sum of natural numbers upto the entered value n.
# Program published on https://beginnersbook.com
# Python program to calculate the sum of n Natural Numbers
# n denotes upto which number you want to calculate the sum
# for example, if n is 5 then the sum of first 5 natural numbers
num = int(input("Enter the value of n: "))
hold = num
sum = 0
if num <= 0:
print("Enter a whole positive number!")
else:
while num > 0:
sum = sum + num
num = num - 1;
# displaying output
print("Sum of first", hold, "natural numbers is: ", sum)
Output 1:
Enter the value of n: 6 Sum of first 6 natural numbers is: 21
Output 2:
Enter the value of n: 0 Enter a whole positive number!
Output 3:
Enter the value of n: -10 Enter a whole positive number!
Output 4:
Enter the value of n: 20 Sum of first 20 natural numbers is: 210

Related Python Examples:
1. Python program to add digits of a number
2. Python program to add subtract multiply and divide two numbers
3. Python program to add two matrices
4. Python program to add two binary numbers
Leave a Reply