Editor

Python Program to Print an Inverted Number Triangle

Beginner · Patterns

An inverted number triangle is a right-angled triangle of numbers with its longest row at the top. Each row counts from 1, and every row is one number shorter than the row above, so 5 rows go from 1 2 3 4 5 down to a single 1.

Program

inverted_number_triangle.py
rows = 5 # or: rows = int(input("Enter the number of rows: "))
for i in range(rows, 0, -1):
# Row i shows the numbers 1 to i
for j in range(1, i + 1):
print(j, end=" ")
print() # move to the next line
Output
1 2 3 4 5 
1 2 3 4 
1 2 3 
1 2 
1

How it works

  1. range(rows, 0, -1) counts down 5, 4, 3, 2, 1, so the first row is the longest.
  2. For each row, the inner loop prints the numbers 1 to i, with a space after each one.
  3. The empty print() ends the row, and the next row is one number shorter.
  4. Printing j, the inner counter, makes every row start at 1, while printing i instead would repeat the row number, like 5 5 5 5 5.

Other ways to write it

Counting down on each row

Counting down on each row
rows = 5
for i in range(rows, 0, -1):
for j in range(i, 0, -1):
print(j, end=" ")
print()
Output
5 4 3 2 1 
4 3 2 1 
3 2 1 
2 1 
1

Counting j down from i makes each row run backwards: 5 4 3 2 1, then 4 3 2 1, and so on down to 1.

Right-aligned inverted triangle

Right-aligned inverted triangle
rows = 5
for i in range(rows, 0, -1):
numbers = " ".join(str(j) for j in range(1, i + 1))
print(" " * (rows - i) + numbers)
Output
1 2 3 4 5
  1 2 3 4
    1 2 3
      1 2
        1

Indenting each row by 2 more spaces, the width of one number and its space, keeps the right edge straight, so the triangle hangs from the right.

Try it yourself

Print the row number on each row instead, so the first row reads 5 5 5 5 5 and the last reads 1.

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