This Python program reads an integer n from the user and calculates the sum of the first n terms of the geometric series:
$$S_n = 1 + \frac{1}{2} + \frac{1}{4} + \frac{1}{8} + \cdots$$
Each term is half of the previous one, starting from 1.
def geometric_sum(n):
total = 0
term = 1
for _ in range(n):
total += term
term /= 2
return round(total, 6)
# Run the program
n = int(input("Enter number of terms: "))
result = geometric_sum(n)
print(f"Sum of first {n} terms: {result}")
Enter number of terms: 5
Sum of first 5 terms: 1.9375
- The first term is 1
- Each subsequent term is divided by 2
- The loop adds each term to the total
- The result is rounded to 6 decimal places for clarity