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 5How it works
" ".join(...)puts one space between the numbers and none after the last one, so no line ends with a space.- Row
iis2 * i - 1characters wide (i digits and i - 1 spaces). Each row is two characters wider than the one above, so one space less in front keeps it centred. - The top row needs
rows - 1spaces in front, and the bottom row needs none. - With 10 rows or more, the two-digit numbers make the rows wider and the shape is no longer even.
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
upis the counting-up part, such as"123".up[-2::-1]starts at the second-to-last character and steps backwards to the start, which gives"21". The middle digit is not repeated.- On row 1,
upis"1"and the slice is empty, so the row is just1. - This version works for up to 9 rows, because each number must be one digit.