Visualizing a Geometric Progression with Python – A creative introduction to coding math sequences.
So, you’ve heard about Geometric Progression (GP) and now you’re curious how to write a Python program for it? Great—you’re in the right place.
A geometric progression is just a sequence where each number is multiplied by the same value to get the next one. For example:
2, 4, 8, 16, 32…
Here, we’re multiplying by 2 each time.
Now instead of calculating each number by hand, wouldn’t it be easier to write a Python program that does it for you? That’s exactly what we’ll do—step by step.
We’ll start by understanding how a GP works, then write a simple Python program to find any term you want—or even generate the whole sequence. No complicated stuff—just clear, beginner-friendly code.
Let’s get started.
Before we jump into the code, let’s quickly understand what a geometric progression (GP) really is.
It’s just a sequence of numbers where each term is multiplied by the same value—called the common ratio—to get the next one.
Here’s the general form of a geometric progression:
a, ar, ar², ar³, …, arⁿ⁻¹
Where:
Let’s make that even clearer with a simple example.
If a = 3 and r = 2, then the sequence would be:
3, 6, 12, 24, 48
We’re just multiplying by 2 each time.
Now that you’ve got the idea, let’s turn this into a Python program—step by step.
Now that we understand what a geometric progression is, let’s think about how we can turn this into a Python program.
To generate a geometric progression, we’ll need the following inputs from the user:
Once we have those inputs, we’ll use a loop to generate each term of the sequence. A loop will help us calculate each term based on the previous one—starting from the first term and multiplying by the common ratio.
To make it easier, we’ll use the following approach:
Now, let’s put this into code!
Now that we understand the logic behind geometric progression, let’s put it into code. Don’t worry—I’ll explain each step along the way!
First, we need to ask the user for three things:
In Python, we can use the input() function to get these values. Since input() always returns a string, we’ll need to convert those values into the correct data type—float for the first term and the common ratio, and int for the number of terms.
Here’s the code for Step 1:
a = float(input("Enter the first term: "))
r = float(input("Enter the common ratio: "))
n = int(input("Enter the number of terms: "))
a = float(input(...)): This line gets the first term from the user and converts it to a float.r = float(input(...)): This gets the common ratio and converts it to a float.n = int(input(...)): This gets the number of terms and converts it to an integer.Now comes the fun part: using a loop to generate the sequence! We’re going to multiply the first term by the common ratio repeatedly to get the next terms in the sequence.
We’ll use a for loop to do this. The loop will run for the number of terms the user wants, and in each loop, we’ll calculate the next term by multiplying the first term by the common ratio raised to the power of the loop index.
Here’s the code for Step 2:
print("The geometric progression is:")
for i in range(n):
term = a * (r ** i)
print(term, end=" ")
for i in range(n):: This loop will run n times, where n is the number of terms the user entered.term = a * (r ** i): In each iteration, we calculate the i-th term of the progression. We multiply the first term by the common ratio raised to the power of i (which is the index of the current term).print(term, end=" "): This prints each term on the same line, separated by spaces.Let’s see how this works with an example. If you enter the following values:
The output will look like this:
Enter the first term: 2
Enter the common ratio: 3
and Enter the number of terms: 5
The geometric progression is:
2.0 6.0 18.0 54.0 162.0
The program generates each term by multiplying the previous one by the common ratio (3), starting with the first term (2). You can see that the sequence is 2, 6, 18, 54, 162.
Here’s the full code we wrote earlier:
a = float(input("Enter the first term: "))
r = float(input("Enter the common ratio: "))
n = int(input("Enter the number of terms: "))
print("The geometric progression is:")
for i in range(n):
term = a * (r ** i)
print(term, end=" ")
Let’s go through each part and explain it clearly.
float is used a = float(input("Enter the first term: "))
r = float(input("Enter the common ratio: "))
input(): This function asks the user to type something into the console (like entering a number). But, it always returns that input as a string. "2" (a string, not a number).float(): Since the first term (a) and common ratio (r) could be decimal numbers (like 2.5, 3.5, etc.), we use float() to convert that string into a number with decimals. float() will convert it into 2.0, which is a float.This is important because we need to work with numbers, not strings, to do math.
n = int(input("Enter the number of terms: "))
input() here gets the number of terms the user wants.int() is used to convert that input into an integer (whole number). This is important because the number of terms in a sequence should always be a whole number (you can’t have a fraction of a term).For example:
int() makes sure it’s treated as 5 (an integer).range(n) doesfor i in range(n):
range(n): This function generates a sequence of numbers starting from 0 up to n-1. If n = 5, range(5) will give us the numbers 0, 1, 2, 3, 4. for i in range(n):: This sets up a loop that repeats n times. Each time the loop runs, i will be one of those numbers from 0 to n-1.For example, if n = 5, the loop will run 5 times, with i taking values 0, 1, 2, 3, 4 on each iteration.
a * (r ** i) calculates each termterm = a * (r ** i)
r ** i): This part is doing the exponentiation or raising to a power. When we write r ** i, we are calculating r raised to the power of i. r ** i would give 3², which is 9.a * (r ** i)): Now, we multiply the result by the first term (a). This is how the program calculates each term in the sequence: it starts with the first term and multiplies by the common ratio raised to the power of the current index (i).
print(term, end=" ")
print(): This function displays the result on the screen. Here, we are printing the value of term (the current term of the sequence).end=" ": By default, print() will add a new line after each term, which would print each term on a new line. But we don’t want that—we want all the terms to appear on the same line, separated by spaces. So, we use end=" " to tell Python to print each term on the same line, with a space between them.r ** i calculates the power of the common ratio, so each term increases by multiplying the previous term by r.print() function shows each term on the same line, separated by spaces.Let’s now modify the program to make it a bit cleaner and add some useful enhancements! We’ll store the terms in a list, calculate the sum of the geometric progression, and use functions to make the code more organized.
Here’s what we’ll cover:
Let’s break it down step-by-step:
Instead of printing each term one by one, we can store all the terms in a list. This will allow us to use the terms later on, if needed, like for calculations (e.g., finding the sum).
You can store the terms using a list comprehension. This is a concise way to create a list in Python.
Here’s how you do it:
gp = [a * (r ** i) for i in range(n)]
print("Geometric progression as a list:", gp)
[a * (r ** i) for i in range(n)]: This is a list comprehension. It creates a list of terms where each term is calculated by a * (r ** i) for each value of i from 0 to n-1.gp: This variable holds the entire list of terms of the geometric progression.Once we have the list of terms, we can easily calculate the sum of the geometric progression using Python’s built-in sum() function. Here’s how you can do that:
print("Sum of the series:", sum(gp))
sum(gp): This function adds up all the terms in the list gp and returns the total.To make the code cleaner and more reusable, we can put everything into a function. This way, you can generate the geometric progression and get the sum with just a function call!
Here’s how you can do it:
def generate_gp(a, r, n):
# Generate the geometric progression
gp = [a * (r ** i) for i in range(n)]
return gp
def main():
# Get user input
a = float(input("Enter the first term: "))
r = float(input("Enter the common ratio: "))
n = int(input("Enter the number of terms: "))
# Generate the geometric progression
gp = generate_gp(a, r, n)
# Print the geometric progression and sum
print("Geometric progression as a list:", gp)
print("Sum of the series:", sum(gp))
# Call the main function to run the program
main()
generate_gp(a, r, n): This function generates the geometric progression and returns it as a list. We take the first term (a), common ratio (r), and number of terms (n) as inputs.
main(): This is where we get the user’s input and then call generate_gp() to generate the sequence. Finally, it prints the geometric progression and the sum.
main() is called at the end of the program to run everything.
Here’s the complete code with all the changes and enhancements:
def generate_gp(a, r, n):
# Generate the geometric progression
gp = [a * (r ** i) for i in range(n)]
return gp
def main():
# Get user input
a = float(input("Enter the first term: "))
r = float(input("Enter the common ratio: "))
n = int(input("Enter the number of terms: "))
# Generate the geometric progression
gp = generate_gp(a, r, n)
# Print the geometric progression and sum
print("Geometric progression as a list:", gp)
print("Sum of the series:", sum(gp))
# Call the main function to run the program
main()
generate_gp(): This function takes the first term, common ratio, and number of terms as input and returns the geometric progression as a list.main(): This function handles user input, calls the generate_gp() function to generate the sequence, and then prints both the progression and its sum.If you enter:
The output will be:
Enter the first term: 2
Enter the common ratio: 3
Enter the number of terms: 5
Geometric progression as a list: [2.0, 6.0, 18.0, 54.0, 162.0]
Sum of the series: 242.0
sum() function to calculate the sum of the geometric progression.Now, you have a more flexible program that can easily be modified or reused in other projects!
When writing your Python program for a geometric progression, there are a few common mistakes you should watch out for. Here’s a checklist of things to keep in mind:
int() Instead of float() and Losing Precisionint() instead of float() when getting input for the first term (a) or common ratio (r), you might lose precision. This can cause errors in your calculations if you’re working with decimal values.float() when you expect decimal numbers (e.g., for the common ratio or first term).Example:
a = float(input("Enter the first term: ")) # Correct
r = float(input("Enter the common ratio: ")) # Correct
^ Instead of ** (Exponentiation in Python)^ is used for bitwise XOR (exclusive OR), not for exponentiation. If you mistakenly use ^, your program won’t raise the powers as expected, leading to incorrect results.** for exponentiation to raise numbers to a power.Example:
term = a * (r ** i) # Correct exponentiation
input() Valuesinput() function in Python always returns a string, so if you try to use the value in mathematical operations without converting it to the appropriate type (e.g., float or int), your program will throw an error.input() values to the appropriate type before using them in calculations.Example:
n = int(input("Enter the number of terms: ")) # Correct for integers
float() for decimal inputs (like first term and common ratio).** for exponentiation, not ^.float() for decimals, int() for whole numbers).By avoiding these simple mistakes, your program will run smoothly and give you the correct results every time!
Python offers some efficient and compact ways to calculate geometric progressions, especially with libraries like NumPy. If you’re looking for a shorter and more concise way to calculate geometric progressions, here’s how you can do it:
NumPy is a popular library for numerical computations in Python. It can significantly simplify your code and improve performance for operations like geometric progressions. Here’s how you can calculate a geometric progression with NumPy:
import numpy as np
# Get user input
a = float(input("Enter the first term: "))
r = float(input("Enter the common ratio: "))
n = int(input("Enter the number of terms: "))
# Generate the geometric progression using NumPy
gp = a * r**np.arange(n)
print("Geometric progression:", gp)
print("Sum of the series:", np.sum(gp))
np.arange(n): This creates an array of integers from 0 to n-1. It is equivalent to range(n) but returns a NumPy array instead of a Python list, which makes operations like exponentiation more efficient.r**np.arange(n): This calculates the common ratio raised to the power of each term index (from 0 to n-1).np.sum(gp): This function calculates the sum of the terms in the geometric progression in a very compact manner.If you enter:
The output will be:
Enter the first term: 2
Enter the common ratio: 3
Enter the number of terms: 5
Geometric progression: [ 2. 6. 18. 54. 162.]
Sum of the series: 242.0
n.If you’re working with more complex calculations or large datasets, NumPy is a great choice. However, if you’re just starting with Python or working on simple projects, the basic for loop method is perfectly fine.
Now that you’ve got the basics down, it’s time to play around with the code a bit. Here are some simple challenges to help you understand geometric progression better and get more comfortable with Python.
a = 3
r = -2
n = 6You’ll get an alternating sequence:3, -6, 12, -24, 48, -96
2. Try r = 1
When the common ratio is 1, what do you expect?
Hint: All terms should be the same because you’re multiplying by 1 every time.
3. Turn your code into a function
Try wrapping your GP logic into a reusable function like this:
def generate_gp(a, r, n):
return [a * (r ** i) for i in range(n)]
print(generate_gp(2, 3, 5)) # Output: [2, 6, 18, 54, 162]
Now you can call this function with any values of a, r, and n.
This is a great way to build confidence, experiment, and understand how small changes in the formula affect the sequence. Once you’re comfortable, try combining this with plots using matplotlib to visualize the progression!
And there you have it! You’ve just learned how to write a Python program to generate a geometric progression, step by step.
We covered:
Plus, you now have a few practice challenges to help lock it all in!
Whether you’re just starting out or brushing up your Python skills, understanding patterns like geometric progressions is a great way to grow more confident in coding.
If you found this helpful and want more beginner-friendly Python tutorials, feel free to visit emitechlogic.com for more guides, projects, and tips!
Ready to take on the next concept? Let’s keep learning—one simple step at a time.
All the terms in the sequence will be the same as the first term, since multiplying by 1 doesn’t change the value.
Yes, but using **float()** helps when working with decimals or fractions, especially if precision is important.
r ** i mean in the code? It means raise the common ratio r to the power of i. For example, 2 ** 3 gives 8.
If the common ratio r is not 1, you can use the formula:
sum = a × (1 – rⁿ) / (1 – r)
But in Python, it’s easier to use:
sum(gp)
after storing the sequence in a list.
Python range() function – Official Docs
Understand how range() works when generating sequences.
Geometric Progression – Khan Academy
A beginner-friendly explanation of geometric sequences with visual examples.
NumPy arange() and vector operations – NumPy Docs
Dive deeper into using NumPy for numerical sequences like GPs.
Geometric Series Formula – Math is Fun
Covers both finite and infinite geometric series with interactive examples.
These links offer clear explanations and hands-on examples—perfect if you want to go beyond the basics or reinforce what you’ve learned.
After debugging production systems that process millions of records daily and optimizing research pipelines that…
The landscape of Business Intelligence (BI) is undergoing a fundamental transformation, moving beyond its historical…
The convergence of artificial intelligence and robotics marks a turning point in human history. Machines…
The journey from simple perceptrons to systems that generate images and write code took 70…
In 1973, the British government asked physicist James Lighthill to review progress in artificial intelligence…
Expert systems came before neural networks. They worked by storing knowledge from human experts as…
This website uses cookies.