Reverse Per-Row Number Triangle in Python

What You’ll Learn
How to print a reverse per-row number triangle in Python using nested for loops. Each row prints digits from the current row number down to 1: 1, 21, 321, 4321, and so on.
This pattern helps you practice counting backwards with range() inside a nested loop.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
21
321
4321
54321Complete Python Program
The outer loop increases the row count. The inner loop counts down from i to 1 and prints each digit.
rows = 5
for i in range(1, rows + 1):
for j in range(i, 0, -1):
print(j, end="")
print()🧠 How It Works
Choose the row count
rows = 5 sets the height of the triangle.
Outer loop (row number)
for i in range(1, rows + 1) moves from row 1 up to row rows.
Inner loop (count down i..1)
for j in range(i, 0, -1) prints digits from the current row number down to 1 using print(j, end="").
New line
print() ends each row.
Reverse per-row triangle
Total digits printed are 1+2+…+n = n(n+1)/2, so time complexity is O(n²) for n rows.
Variation — User Input Version
Let the user decide the number of rows at runtime using input():
rows = int(input("Enter the number of rows: "))
for i in range(1, rows + 1):
for j in range(i, 0, -1):
print(j, end="")
print()💡 Tips for Enhancement
Try These
- Validate input (reject
rows < 1) before printing the pattern - Add spaces between numbers with
print(j, end=" ") - Print an ascending row version by changing the inner loop to
range(1, i + 1) - Right-align the triangle by printing leading spaces before each row
- Replace numbers with letters to create alphabet triangles
Avoid
- Forgetting
print()between rows - Using the wrong step value in
range()when counting down - Mixing up row control and column control (outer loop should define the row)
- Assuming user input is always valid (wrap
int()conversion if needed)
Key Takeaways
The outer loop controls how many rows to print (from 1 to rows).
The inner loop counts down from i to 1, which reverses each row.
Total printed digits follow the triangular number count: n(n+1)/2.
Reverse range() loops make it easy to print descending sequences.
❓ Frequently Asked Questions
range(i, 0, -1), which counts down from i to 1.print(j, end=" "). If you want consistent alignment, print with a fixed width.for j in range(1, i + 1). That prints each row in ascending order.Explore More Python Number Patterns!
Keep going to discover more number pattern programs and strengthen your loop skills.
Reverse ranges like range(n, 0, -1) are a common Python trick for counting down. Combining them with nested loops makes many reverse triangles easy to generate.
12 people found this page helpful
