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

First N Terms of GP

Generate geometric-progression terms with Python exponentiation. Students follow zero-based positions, repeated ratios, and the difference between ** and XOR.

IntermediatePhase 2 - Level 3: Mathematical & Logical PatternsExample 10 of 13
first-n-terms-of-gp.py
1# Take inputs
2a = int(input("Enter first term (a): "))
3r = int(input("Enter common ratio (r): "))
4n = int(input("Enter number of terms (n): "))
5
6# Print GP
7print(f"First {n} terms of GP:")
8for i in range(n):
9 term = a * (r ** i)
10 print(term, end=" ")
11print()

Output

Enter first term (a): 2
Enter common ratio (r): 3
Enter number of terms (n): 5
First 5 terms of GP:
2 6 18 54 162

In this one

  • Use a common ratio
  • Raise to zero-based powers
  • Recognize exponentiation syntax

How it works

  1. 1

    Read a, r, and n.

  2. 2

    Visit the n zero-based positions.

  3. 3

    Print a * (r ** i) for each.

Edge cases

Can r be zero?

Can r be zero?

Yes. The first term is a, then later terms are zero.

Can r be negative?

Can r be negative?

Yes. Nonzero terms can alternate signs.

What's going on

The formula a * (r ** i) multiplies the first term by the ratio raised to its position. At i equal to zero, the power is one.

range(n) produces n positions. For a equal to two and r equal to three, terms begin 2, 6, 18. Python uses ** for powers; ^ would perform bitwise XOR and give the wrong sequence.

Can r be zero? Yes. The first term is a, then later terms are zero.

Can r be negative? Yes. Nonzero terms can alternate signs.

Quiz

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

Question 1

Which operator raises the ratio to a power?

Pick an answer to check it.

Question 2

Can r be zero?

Pick an answer to check it.

Questions people ask

Can r be zero?

Yes. The first term is a, then later terms are zero.

Can r be negative?

Yes. Nonzero terms can alternate signs.

Which operator raises the ratio to a power?

**.