Descending Prefix Number Triangle in Python

What You’ll Learn
How to print a descending prefix number triangle in Python using nested for loops. Each row starts with rows and extends by one more digit to the right: 5, 54, 543, and so on until 54321.
This pattern is a great exercise for combining an increasing row length with a descending sequence inside the inner loop.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
5
54
543
5432
54321Complete Python Program
The outer loop grows the row length. The inner loop prints from rows down to a cutoff based on that length.
rows = 5
for i in range(1, rows + 1):
for j in range(rows, rows - i, -1):
print(j, end="")
print()🧠 How It Works
Choose the row count
rows = 5 sets the starting digit for every row.
Outer loop (row length)
for i in range(1, rows + 1) increases the row length from 1 up to rows.
Inner loop (print rows down)
for j in range(rows, rows - i, -1) prints a descending sequence: rows, rows-1, ..., rows-i+1.
New line
print() ends the row so the next row starts on a new line.
Descending prefix 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(rows, rows - i, -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 the ascending prefix (12345, 1234, ...) by changing the inner loop direction
- Right-align the triangle by printing leading spaces before each row
- Replace numbers with characters to create alphabet prefixes
Avoid
- Forgetting
print()between rows - Using the wrong step value in
range()when counting down - Mixing up the stop value (remember it is exclusive)
- Assuming user input is always valid (wrap
int()conversion if needed)
Key Takeaways
The outer loop increases the row length from 1 to rows.
The inner loop counts down from rows to build each prefix.
Total printed digits follow the triangular number count: n(n+1)/2.
Reverse ranges like range(a, b, -1) are perfect for descending patterns.
❓ Frequently Asked Questions
i each iteration, and the inner loop prints exactly i numbers.rows to the maximum number you want to start with (like 7) and the prefix will start at that number.i.Explore More Python Number Patterns!
Keep going to discover more number pattern programs and strengthen your loop skills.
Even though the digits are printed in descending order, the total amount of output is still a triangular number: 1+2+…+n = n(n+1)/2. That’s why it scales like O(n²).
12 people found this page helpful
