Python Program to Find the Sum of Natural Numbers – 2024

Hey guys, in this blog we will see a Python Program to Find the Sum of Natural Numbers.

Example 1: Using While Loop

# Python Program to Find the Sum of Natural Numbers

num = int(input("Enter a positive number -> "))

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

Output

Enter a positive number -> 4
The sum is -> 10
Enter a positive number -> 5
The sum is -> 15
Enter a positive number -> 6
The sum is -> 21
  • In this way, we have simply declared a sum variable and we keep on adding the number to this variable.
  • Also simultaneously we are reducing our original number in every iteration.
  • Suppose the user inputs 4, our program will add 4 to sum which is currently 0, and reduce our org number 4 to 3, now in the next iteration our program will add 3 to sum, now sum becomes 7 and num becomes 2 and in this way when num becomes 0, our loop will break.

Example 2: Using the formula

sum = n*(n+1)/2

# Sum of natural numbers up to num

num = int(input("Enter a positive number -> "))

if num < 0:
    print("Enter a positive number")
else:
    sum = (num*(num+1))//2
    print("The sum is ->", sum)

Output

Enter a positive number -> 8
The sum is -> 36
Enter a positive number -> 9
The sum is -> 45
Enter a positive number -> 10
The sum is -> 55
  • This is the easiest way of calculating the sum of all natural numbers till a positive number.
  • Suppose n=8, so the sum of all natural numbers till 8 will be (8*9)/2 which equals 36.

Check out our other python programming examples

Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 514

Leave a Reply

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