← Back

Home › Python programs

Sum of N Natural Numbers in Python

इसे Hindi में पढ़ें

Problem statement

Add the numbers 1 through N. For N = 5 the answer is 15 (1+2+3+4+5). Handle N = 0 gracefully — the empty sum is 0.

Approach 1: simple loop

Loop from 1 to N and keep adding into an accumulator. The pattern is the same one behind every running total in every program you will write.

n = 5
total = 0

for i in range(1, n + 1):
    total = total + i

print(total)
# Output: 15

Remember that range(1, n + 1) is needed because the stop value is exclusive — range(1, n) would stop one number early.

Approach 2: reusable function

Gauss's formula does it in one step: n × (n + 1) / 2. Wrap it in a function and use integer division // so the answer stays an integer.

def sum_to(n):
    return n * (n + 1) // 2

print(sum_to(5))       # 15
print(sum_to(100))     # 5050
print(sum_to(0))       # 0

The formula is O(1) — one multiplication whether N is 5 or 5 billion. The loop is O(N). Same answer, wildly different cost.

Approach 3: Pythonic alternative

Python's built-in sum() adds anything iterable, and range is iterable — so the loop collapses into one clear line.

n = 5
print(sum(range(1, n + 1)))   # 15

This is the idiomatic middle ground: no manual accumulator to get wrong, and the intent — "sum of the numbers 1..n" — reads off the page.

Dry run

Trace the loop for n = 5. Start: total = 0. After i=1: 1. After i=2: 3. After i=3: 6. After i=4: 10. After i=5: 15. Then cross-check with the formula: 5 × 6 // 2 = 30 // 2 = 15. Two methods agreeing is the strongest verification a small program can have — and the same pair (trace + formula) catches off-by-one range bugs instantly: range(1, n) would give 10, and 10 ≠ 15 exposes it.

Common errors

Practice on PyDebug

Turn the idea into a debugging habit with these free browser exercises: