Home / Python / Example programs / Loops and numbers

Python program: Print a pyramid pattern

Print triangle and pyramid patterns with nested loops and string repetition.

The code

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))

print()
for i in range(1, rows + 1):
    print(" ".join(str(n) for n in range(1, i + 1)))

Output

*
**
***
****
*****

    *
   ***
  *****
 *******
*********

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

How it works

Each row is built from repeated strings: "*" * 3 is "***". Leading spaces centre the pyramid. Pattern programs are a classic way to practise loops.

Python features used

Learn the ideas behind it in the free lesson Loops.