Alternating Series Sum

Calculate 1 - 1/2 + 1/3 - 1/4 + ... ± 1/n.

IntermediatePhase 2 - Level 3: Mathematical & Logical PatternsExample 13 of 13
alternating-series-sum.py
1# Take n
2n = int(input("Enter n: "))
3
4# Calculate sum
5sum_alt = 0
6for i in range(1, n + 1):
7 if i % 2 == 1:
8 sum_alt += 1 / i
9 else:
10 sum_alt -= 1 / i
11
12print(f"Sum: {sum_alt:.4f}")

Output

Enter n: 5
Sum: 0.7833

What's going on

Alternate signs based on position.

Key Concepts:

Add for odd positions
Subtract for even positions
Create alternating pattern