codescracker


python

Python Program to Find Sum of Natural Numbers



« Previous Program Next Program »


Find Sum of Natural Numbers in Python

To find sum of natural numbers in python, you have to ask from user to enter the total number of term upto which he/she want to find the sum of all natural numbers upto the desired term and then print the summation result as output as shown in the program given below.

Python Programming Code to Find Sum of Natural Numbers

Following python program ask from user to enter the limit to find the sum of all natural numbers upto that limit:

# Python Program - Find Sum of Natural Numbers

print("Enter '0' for exit.");
num = int(input("Upto which number ? "));
if num == 0:
    exit();
elif num < 1:
    print("Kindly try to enter a positive number..exiting..");
else:
    sum = 0;
    while num > 0:
    	sum += num;
    	num -= 1;
    print("Sum = ", sum);

Here is the sample run of the above Python program to illustrate how to find and print sum of natural numbers upto to the given term. That is if user enter 10 then the above program will find the sum of all the natural numbers from 1 to 10, that is, 1+2+3+4+5+6+7+8+9+10.

This is the initial output asking from user to enter the limit or term upto which he/she want to find the sum of all natural numbers upto that term.

find sum of natural numbers python

Now let's provide 10 as the limit and press enter to see the following sample output:

natural number sum python

Below is the same program written and run on python shell:

python find sum of natural numbers

Program Video with Compile and Run


« Previous Program Next Program »








Tools
Calculator

Quick Links
Signup - Login - Give Online Test