Python - Find the Sum of Natural Numbers

In this program, you will learn how to find the sum of natural numbers.


Natural numbers are part of real numbers, that include only the postive integers i.e 1,2,3,4,5,..... exluding zero, fractions, decimals and negative numbers.

Program Code



    # Sum of natural numbers up to given numbers

    # Enter the number
    num = int(input('Enter the number : '))
    
    if num < 0:
        print('Enter a positive number')
    else:
        sum = 0
        while(num > 0): #iterate while loop until num is zero
            sum += num
            num -= 1
        print('The sum is ', sum)

Output



    Enter the number : 20
    The sum is  210

In this program, the variable num is used to holds the given natural number. The sum is initialized to 0.

Then, the while loop to iternate until num becomes zero. We have added the num to sum in each iteration and the value of num is decreased by 1.
Finally, print sum after while loop completed.

We can also use the following formula to find the sum of natual numbers.

    sum = n*(n+1)/2  
            
For example, if n = 10, the sum would be (10*11)/2 = 55



The following topics can be useful to understand this program.



Related Tutorials