Sum of Series 1/1 + 1/2 + … + 1/N in Python

Compute the sum of the harmonic series up to N terms.

BeginnerLoop ProgramsExample 20 of 25
sum-of-series-1-1-1-2-1-n.py
Run in browser
1# Program to compute sum of series 1/1 + 1/2 + ... + 1/N
2
3n = int(input("Enter a positive integer N: "))
4
5if n <= 0:
6 print("Please enter a positive integer.")
7else:
8 total = 0.0
9 for i in range(1, n + 1):
10 total += 1 / i
11 print(f"Sum of series up to 1/{n} is {total}")

Output

Enter a positive integer N: 5
Sum of series up to 1/5 is 2.283333333333333

What's going on

We add each reciprocal 1/i in a loop from 1 to N, accumulating the sum in a float.