Patterns and small projects · beginner
Python Program to Print a Star Pattern (Pyramid)
Print star patterns in Python: a right triangle, a centred pyramid and an inverted triangle, built with nested loops and string multiplication.
- nested loops
- string multiplication
- range()
- print(end=...)
Pattern programs are a favourite in exams and interviews because they test whether you can turn a picture into loop counters. The trick is to work out, for each row, how many spaces and how many stars it needs.
For a pyramid of 5 rows, row i (counting from 1) has 5 - i spaces followed by 2 × i - 1 stars.
The program
rows = 5
for i in range(1, rows + 1):
print("*" * i)
print()
for i in range(1, rows + 1):
print(" " * (rows - i) + "*" * (2 * i - 1))*
**
***
****
*****
*
***
*****
*******
*********How it works
- range(1, rows + 1) counts the rows from 1 to 5.
- "*" * i repeats the star i times, so the first loop prints a right-angled triangle.
- For the pyramid, " " * (rows - i) adds the leading spaces that centre each row: 4 spaces on the first row, none on the last.
- "*" * (2 * i - 1) gives the odd numbers of stars 1, 3, 5, 7, 9, so each row is two stars wider than the one above.
Watch it run line by line
Step through the pyramid loop and look at "Output so far": a new row appears after each print, and i in the global frame tells you which row is being drawn.
“Visualize step by step” opens the program in the Python Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.
Another way: Nested loops, the classic way
Without string multiplication, an inner loop prints one star at a time with end="" so the stars stay on the same line. This is how the pattern is written in C or Java.
rows = 4
for i in range(rows, 0, -1):
for j in range(i):
print("*", end=" ")
print()* * * *
* * *
* *
* Common mistakes
- Forgetting the empty print() after the inner loop, so every star ends up on one line.
- Starting range at 0, which prints an empty first row.
- Getting the spaces wrong for the pyramid: the number of spaces must go down as the stars go up.
Try it yourself
- Print a diamond: the pyramid followed by the inverted pyramid.
- Print a number triangle where row i shows the numbers 1 to i.
- Read the number of rows with input().
Open the program in the Python Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 Python examples, or write your own program in the online Python Compiler.