Step 01 Beginner Problems — Patterns
Pattern 7 — Star Pyramid
A centered pyramid of stars: a single star at the top, and each row below widens by two stars — one stepping left, one stepping right — until the base spans 2n - 1 stars. This is the first pattern that needs two inner ideas at once: leading spaces to center the row, and an odd star count 2i + 1.
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
How to think about it
Number the rows i = 0, 1, ..., n-1. Row i prints n - i - 1 blank slots followed by 2i + 1 stars. The star count is always odd — 1, 3, 5, ... — because the pyramid grows symmetrically around a fixed center column. The blank count shrinks by one per row (n - i - 1), which pulls each row's left edge one slot outward. In this spaced rendering each slot is two characters wide (a token plus its separating space), so the indent is (n - i - 1) pairs of spaces. The base row (i = n - 1) has zero blanks and 2n - 1 stars.
Code
The code computes the indent as ' ' * (n - i - 1) — two spaces per empty slot so the stars line up with the rows below — and joins 2i + 1 '*' tokens for the body, then prints indent + body. Try replacing the double-space indent with a single space and watch the pyramid lean: the alignment lives in that detail.
def pattern(n):
for i in range(n):
indent = " " * (n - i - 1)
stars = " ".join(["*"] * (2 * i + 1))
print(indent + stars)Key points
- Row i: blanks = n - i - 1, stars = 2i + 1 — the two formulas move in opposite directions.
- Pyramid widths are the odd numbers 1, 3, 5, ..., 2n - 1.
- Each blank slot must be as wide as a printed token (2 chars here), or the centering breaks.
- The center column never moves; every row is symmetric around it.
- Base check: the last row has 0 leading blanks and exactly 2n - 1 stars.