PythonMastery

Sum of a series in Python

Add up the series 1 + 2 + ... + n, 1² + 2² + ... + n² and 1 + 1/2 + ... + 1/n with a loop, and check them with the formulas.

A series is a sum of terms that follow a rule. This program adds up three common series with one loop: the numbers 1 to n, their squares, and the fractions 1/1 to 1/n.

The program

python
n = int(input("Enter n: "))

sum_n = 0
sum_squares = 0
harmonic = 0.0

for i in range(1, n + 1):
    sum_n += i
    sum_squares += i * i
    harmonic += 1 / i

print("1 + 2 + ... + n      =", sum_n)
print("1² + 2² + ... + n²   =", sum_squares)
print(f"1 + 1/2 + ... + 1/n  = {harmonic:.4f}")

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

output
Enter n: 10
1 + 2 + ... + n      = 55
1² + 2² + ... + n²   = 385
1 + 1/2 + ... + 1/n  = 2.9290

How it works

Using the formulas

The first two series have formulas that give the answer with no loop: 1 + 2 + ... + n = n(n + 1) / 2, and 1² + 2² + ... + n² = n(n + 1)(2n + 1) / 6. The sum of cubes is the square of the first one. sum() with a generator gives the same results as the loop, so you can compare:

python
n = 10

print(sum(range(1, n + 1)), n * (n + 1) // 2)
print(sum(i * i for i in range(1, n + 1)), n * (n + 1) * (2 * n + 1) // 6)
print(sum(i ** 3 for i in range(1, n + 1)), (n * (n + 1) // 2) ** 2)
output
55 55
385 385
3025 3025

// keeps the results as whole numbers. The division is always exact, because n(n + 1) is always even. The sum of natural numbers page explains why the first formula works.

The harmonic series has no simple formula

There is no short exact formula for 1 + 1/2 + ... + 1/n. For large n, it is close to ln(n) + 0.5772, where 0.5772... is a constant called the Euler-Mascheroni constant:

python
import math

n = 1000
harmonic = sum(1 / i for i in range(1, n + 1))
estimate = math.log(n) + 0.5772156649

print(f"Loop:     {harmonic:.6f}")
print(f"Estimate: {estimate:.6f}")
output
Loop:     7.485471
Estimate: 7.484971

The harmonic series grows without limit, but very slowly: you need more than 12,000 terms to pass 10.

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