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.

# 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

Thought of the day-

“Logic will take you from A to B. Imagination will take you everywhere.”- Albert Einstein

Read This-

मई जून की गरमी , तापमान 50 डिग्री से ऊपर ऐसे में घर की छत ऐसे तपती है जैसे आग | तपती  छत की गरमी को कम करने के लिए वैसे तो कई उपाय बताए जाते है | लेकिन जो सबसे बेस्ट उपाय है , वो हैं घर की छत पर सफ़ेद पेंट से पुताई | ऐसा करने से आपको इंस्टेंट रिजल्ट ( Instant Result ) मिलते हैं | और गरमी की तपती दुपहरी में छत भी कम तपती है | लेकिन ऐसा आखिर होता क्यूँ है | आज हम को यही बताने जा रहे है की घर की छत पर सफ्र्द पेंट से पुताई करने से आखिर गर्मी कम क्यों हो जाती है |

देश के कई क्षेत्रो में गरमी का प्रकोप बहुत ज्यादा होता है , खासतौर से मिडिल क्लास परिवारों के लिए यह बहुत ही मुश्किलों से भरा दौर होता है |

independently created by a human author and possesses at least some minimal degree of creativity.

the fair use of a copyrighted work for purposes such as criticism, comment, news reporting, teaching (including multiple copies for classroom use), scholarship, or research, is not an infringement of copyright. 

Fair use is a doctrine in the copyright law that allows limited use of copyrighted material without requiring permission from the rights holders, such as for commentary, criticism, news reporting, research, teaching or scholarship.  It provides for the legal, non-licensed citation or incorporation of copyrighted material in another author’s work under a four-factor balancing test.  The term “fair use” originated in the United States.  A similar principle, fair dealing, exists in some other common law jurisdictions.  Civil law jurisdictions have other limitations and exceptions to copyright. 

Leave a Reply

Your email address will not be published. Required fields are marked *