Python program to find the sum of n natural numbers

In this program we will learn how to calculate the sum of natural numbers from 1 to the number that the user enters.
For example if the user enters 5, the output would be 15, i.e., 1 + 2 + 3 + 4 + 5

To understand this example, you should know the following topics in python programming –

  • Variables
  • Conditional statements
  • Loops (We will use while loop in this program)

Program

num = int(input("Enter a number"))
result = 0
i = 0
if num < 0:
    print("Please enter a positive number")
else:
    while i <= num:
        result += i
        i += 1
    print("The sum is", result)

Output

Enter a number10

The sum is 55

Explanation

  • First of all we are asking the user to enter a number and storing it in the variable named num.
  • Then we have declared two variables named result and i and initialized them both with 0.
  • Next we have mentioned an if else statement. Inside the if statement, we have put a condition that checks if the number is less than zero. If the condition is true, a message would be displayed that says “Please enter a positive number” and the program would terminate.
  • If the condition of if statement is false (if the number entered by user is greater than zero), then else part would be executed. In the else statement we have used a while loop that would work until the value of i is less than the number entered by the user. With each iteration of the loop a sum of result and i is generated and get stored inside the result variable again and again.
  • Lastly the calculated value would be displayed along with a message.

Alternative Method

The mathematical formula to calculate the sum of n natural numbers is n * (n + 1)/2, where n is the number up to which the sum is to be calculated. We can make the program without using the loop by implementing this formula directly in our program.

num = int(input("Enter a number")) 
if num < 0: 
    print("Please enter a positive number") 
else : 
    result = num * (num + 1)/2 
print("The sum is", result)