PythonMastery

Sum of first N natural numbers in Python

Add up 1 + 2 + ... + n three ways: with a while loop, with sum(range()), and with the formula n(n+1)/2. All three give 5050 for n = 100.

The natural numbers are 1, 2, 3 and so on. This program adds the first n of them, first with a loop and then with a formula that needs no loop at all.

The program

python
n = int(input("Add the numbers from 1 to: "))

total = 0
i = 1
while i <= n:
    total += i
    i += 1

print(f"Sum of 1 to {n} = {total}")

Typed in this example: 100. Press Run to type your own.

output
Add the numbers from 1 to: 100
Sum of 1 to 100 = 5050

How it works

Two shorter ways

sum() adds up everything in a range. The formula n * (n + 1) // 2 gives the same answer with one multiplication, however large n is.

python
n = 100

print(sum(range(1, n + 1)))
print(n * (n + 1) // 2)
output
5050
5050

The formula works because you can pair the numbers from both ends: 1 + 100, 2 + 99, 3 + 98, and so on. Each pair adds up to n + 1, and there are n / 2 pairs. // is whole-number division, so the result is an int and not 5050.0.

Related programs: Sum of a series.

Learn the idea: Loops: for, while, and the Pythonic Patterns, Operators & Expressions