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
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1How it works
- The outer loop picks the row, and row
ihas its largest number,i, in the middle. - 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). - The first inner loop counts up from 1 to
i, and the second counts back down fromi - 1to 1 withrange(i - 1, 0, -1). - 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
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
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises