Editor

Python Program to Print a Number Pyramid

Beginner · Patterns

A number pyramid is a centred triangle of numbers in which each row counts up to the row number and back down again: 1, then 1 2 1, then 1 2 3 2 1, and so on. The largest number sits in the middle of each row, so every row reads the same from both ends.

Program

number_pyramid.py
rows = 5 # or: rows = int(input("Enter the number of rows: "))
for i in range(1, rows + 1):
# Two spaces for each row still to come, to centre this one
print(" " * (rows - i), end="")
# Count up from 1 to i
for j in range(1, i + 1):
print(j, end=" ")
# Count back down from i - 1 to 1
for j in range(i - 1, 0, -1):
print(j, end=" ")
print() # move to the next line
Output
        1 
      1 2 1 
    1 2 3 2 1 
  1 2 3 4 3 2 1 
1 2 3 4 5 4 3 2 1

How it works

  1. The outer loop picks the row, and row i has its largest number, i, in the middle.
  2. Each number takes 2 characters (the digit and a space), so the row is indented by 2 spaces for every row still to come, " " * (rows - i).
  3. The first inner loop counts up from 1 to i, and the second counts back down from i - 1 to 1 with range(i - 1, 0, -1).
  4. The layout lines up for up to 9 rows, because after that the numbers have two digits and push the rows out of place.

Other ways to write it

Simple number pyramid

Simple number pyramid
rows = 5
for i in range(1, rows + 1):
numbers = " ".join(str(j) for j in range(1, i + 1)) # "1 2 3"
print(" " * (rows - i) + numbers)
Output
    1
   1 2
  1 2 3
 1 2 3 4
1 2 3 4 5

Here each row just counts from 1 to i, and since each row is 2 characters wider than the one above, 1 space less of indent per row keeps it centred.

Same number on each row

Same number on each row
rows = 5
for i in range(1, rows + 1):
print(" " * (rows - i) + (str(i) + " ") * i)
Output
    1 
   2 2 
  3 3 3 
 4 4 4 4 
5 5 5 5 5

(str(i) + " ") * i repeats the row number, so the rows read 1, 2 2, 3 3 3 and so on.

Try it yourself

Print letters instead of numbers with chr(64 + j), so the third row reads A B C B A.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises