PythonMastery

Number pyramid pattern in Python

Print a centred pyramid of numbers with a for loop, then a palindrome pyramid where each row counts up and back down: 1, 121, 12321.

Row i of the pyramid holds the numbers 1 to i, with a space between them. Spaces in front of each row push it to the centre.

The program

python
rows = int(input("Number of rows: "))

for i in range(1, rows + 1):
    spaces = " " * (rows - i)
    numbers = " ".join(str(n) for n in range(1, i + 1))
    print(spaces + numbers)

Typed in this example: 5. Press Run to type your own.

output
Number of rows: 5
    1
   1 2
  1 2 3
 1 2 3 4
1 2 3 4 5

How it works

For the same shape with stars, see the star triangle pattern.

A palindrome pyramid

Each row counts up to i and back down again, so it reads the same from both ends:

python
rows = 5

for i in range(1, rows + 1):
    up = "".join(str(n) for n in range(1, i + 1))
    down = up[-2::-1]
    print(" " * (rows - i) + up + down)
output
    1
   121
  12321
 1234321
123454321

Learn the idea: Loops: for, while, and the Pythonic Patterns, Working with Strings