A Program to Calculate the Sum of Natural Numbers

In this example, we are giving a program to calculate the sum of n natural numbers.


Program to calculate the sum of n natural number:

  1. # Calculate the sum of n natural number
  2. num = int(input('Enter a number: '))
  3. if num < 0:
  4. print("Enter a positive number")
  5. else:
  6. sum = 0
  7. while(num > 0):
  8. sum += num
  9. num -= 1
  10. print("The sum is", sum)

Output:

Enter a number: 17
The sum is 153