Editor

Python Program to Find the Sum of Natural Numbers

Beginner · Numbers

Natural numbers are the counting numbers 1, 2, 3, 4 and so on. This program adds up the first n natural numbers with a loop, and then checks the answer with the formula n x (n + 1) / 2.

Program

sum_of_natural_numbers.py
n = 10 # or: n = int(input("Enter a positive number: "))
if n < 1:
print("Please enter a positive number")
else:
total = 0
for i in range(1, n + 1):
total += i # add each number to the running total
print(f"Sum of the first {n} natural numbers: {total}")
# The formula gives the same answer without a loop
formula = n * (n + 1) // 2
print(f"Using the formula n(n + 1)/2: {formula}")
Output
Sum of the first 10 natural numbers: 55
Using the formula n(n + 1)/2: 55

How it works

  1. Natural numbers start from 1, so a number below 1 is rejected first.
  2. range(1, n + 1) gives the numbers 1 to n, because range() stops one before its end value.
  3. total += i adds each number to the running total, so after the loop total holds 1 + 2 + ... + n.
  4. The formula n * (n + 1) // 2 gives the same result straight away; n * (n + 1) is always even, so // loses nothing.

Other ways to write it

Using a while loop

Using a while loop
n = 10
total = 0
i = 1
while i <= n:
total += i
i += 1
print("Sum of 1 to", n, "is", total)
Output
Sum of 1 to 10 is 55

A while loop does the same work but needs its own counter i, which must go up each time or the loop never ends.

Using sum() and range()

Using sum() and range()
n = 100
print(f"Sum of 1 to {n} is {sum(range(1, n + 1))}")
Output
Sum of 1 to 100 is 5050

sum() adds up everything in the range in one call. For n = 100 it gives 5050, the answer the young mathematician Gauss is said to have found in seconds.

Try it yourself

Change the loop so it adds only the even numbers from 1 to n.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises