Pyramid Star Pattern in Python

What You'll Learn
This program prints a centered pyramid. Each next row adds 2 stars so the pyramid grows symmetrically.
For row i (starting at 1), print rows - i spaces and 2 * i - 1 stars.
⭐ Pattern Output
When you run the program with rows = 5:
*
***
*****
*******
*********Complete Python Program
Fixed rows = 5 version:
rows = 5
for i in range(1, rows + 1):
for _ in range(rows - i):
print(" ", end="")
for _ in range(2 * i - 1):
print("*", end="")
print()🧠 How It Works
Setup
rows is the pyramid height. for i in range(1, rows + 1): walks from one star on row 1 to a bottom row of 2 * rows - 1 stars.
Margin: print(" ", end="")
for _ in range(rows - i): prints rows - i spaces so the odd-width star block sits centered.
Stars: print("*", end="")
for _ in range(2 * i - 1): prints 1, 3, 5, …, 2*rows-1 asterisks—always odd so the pyramid has one peak star. String form: print(" " * (rows - i) + "*" * (2 * i - 1)).
New line
print() ends the row. Row i prints (rows - i) + (2i - 1) = rows + i - 1 characters before the newline.
Symmetric pyramid
Total stars n² (sum of odd lengths 1 through 2n-1); O(n²) output for n = rows, O(1) extra space. The bottom row scrolls horizontally in the green preview on narrow screens. Same core idea as the top half of Program 10.
Variation — User Input Version
Read rows from user input:
rows = int(input("Enter the number of rows: "))
for i in range(1, rows + 1):
print((" " * (rows - i)) + ("*" * (2 * i - 1)))💡 Tips for Enhancement
Try These
- Print a hollow pyramid by printing stars only at the edges
- Use a different character (like
#) - Add spaces between stars (e.g.,
"* " * (2*i-1)) for a wider look - Validate input (reject
rows < 1) - Try the inverted pyramid next (Program 6)
Avoid
- Using even star counts (symmetry breaks)
- Mixing tabs and spaces for alignment
- Printing trailing spaces after the stars
- Forgetting to reset row formatting each loop
- Assuming user input is always valid
Key Takeaways
Row i prints rows - i spaces and 2 * i - 1 stars.
Odd star counts keep the pyramid symmetric.
The last row prints 2 * rows - 1 stars.
Time complexity is O(n²) due to printing \(\Theta(n^2)\) characters.
This pyramid is the foundation for diamond patterns (Programs 9 and 10).
❓ Frequently Asked Questions
(" " * (rows - i)) + ("*" * (2*i - 1)) and print it.n rows, since total printed characters are \(\Theta(n^2)\).Next: Inverted Pyramid Pattern
Continue to Program 6 to print the inverted pyramid in Python.
If you remove the leading spaces, the pyramid becomes left-aligned and no longer looks centered.
9 people found this page helpful
