Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Geometric Series Sum

Sum a finite geometric series with powers and a loop. Students accept decimal terms and ratios and see why the ratio-one case works without a special formula.

IntermediatePhase 6 - Category 4: Mathematical CombinationsExample 5 of 10
geometric-series-sum.py
1# Take inputs
2a = float(input("Enter first term (a): "))
3r = float(input("Enter common ratio (r): "))
4n = int(input("Enter number of terms (n): "))
5
6# Calculate sum
7total = 0
8for i in range(n):
9 total += a * (r ** i)
10
11print(f"Sum: {total}")

Output

Enter first term (a): 2
Enter common ratio (r): 3
Enter number of terms (n): 4
Sum: 80.0

In this one

  • Generate finite ratio terms
  • Use a zero-based exponent
  • Handle ratio one naturally

How it works

  1. 1

    Read a, r, and n.

  2. 2

    Add a * (r ** i) for n zero-based positions.

  3. 3

    Print the combined floating-point result.

Edge cases

What happens when r = 1?

What happens when r = 1?

The loop adds a once for each requested term.

What happens when n = 0?

What happens when n = 0?

The total remains zero.

What's going on

The term at index i is a * (r ** i). range(n) begins at zero, so the first contribution is a.

Each term is added to total. When r equals one, every term is a and no formula denominator becomes zero. Negative ratios can alternate signs, and floating-point inputs can introduce rounding. The number of terms, not a value threshold, controls stopping.

What happens when r = 1? The loop adds a once for each requested term.

What happens when n = 0? The total remains zero.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What power is used for the first term?

Pick an answer to check it.

Question 2

What happens when r = 1?

Pick an answer to check it.

Questions people ask

What happens when r = 1?

The loop adds a once for each requested term.

What happens when n = 0?

The total remains zero.

What power is used for the first term?

Zero.