Python program to calculate sum of n natural numbers

Python program to calculate sum of n natural numbers

Python program to calculate sum of n natural numbers

In this example we will learn how to calculate sum of n natural numbers

1. Python program for sum of n numbers using While Loop

#Python program to calculate the addition of 1 to 10 using While Loop
n=int ( input( ” Enter any number : ” ) )
if (n < 0):
    print(” Please Enter positive number “)
else:
    sum = 0
    while( n > 0):
        sum += n
        n -= 1
    print(‘Addition of all numbers = ‘,sum)

Output

Enter any number : 10
Addition of all numbers = 55

2. Python program for sum of n numbers using For Loop

#Python program to calculate the addition of 1 to 10 using For Loop
n=int ( input( ” Enter any number : ” ) )
if (n < 0):
    print(” Please Enter positive number “)
else:
    sum = 0
    for i in range (n+1):
        sum += i
        
    print(‘Addition of all numbers = ‘,sum)

Output

Enter any number : 10
Addition of all numbers = 55

If you like my post please share it with your friends by simply clicking the below social media button, and Don’t forget to comment so we will update ourselves.

Share in a Single Click

Leave a Reply

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