Reverse Shifted Number Triangle in Python

What You’ll Learn
How to print a reverse shifted number triangle in Python using nested for loops. The first row prints just rows, then each next row starts one number earlier, building up to 1..rows.
This pattern is a great way to practice descending row control while printing an ascending sequence on each row.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
5
45
345
2345
12345Complete Python Program
The outer loop chooses the start value (from rows down to 1). The inner loop prints from that start up to rows.
rows = 5
for i in range(rows, 0, -1):
for j in range(i, rows + 1):
print(j, end="")
print()🧠 How It Works
Choose the row count
rows = 5 sets the maximum digit printed.
Outer loop (decreasing start)
for i in range(rows, 0, -1) selects the starting number for each row: 5, 4, 3, 2, 1.
Inner loop (print i..rows)
for j in range(i, rows + 1) prints numbers from the current start i up to rows using print(j, end="").
New line
print() ends the row and moves to the next line.
Reverse shifted triangle
Total numbers 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(rows, 0, -1):
for j in range(i, rows + 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 non-reverse shifted pattern by looping
iupward (Program 2 style) - Right-align the triangle by printing leading spaces before each row
- Replace numbers with letters to create alphabet versions
Avoid
- Forgetting
print()between rows - Mixing up the
range()endpoints (stop value is exclusive) - Using negative or zero rows without validating input
- Assuming user input is always valid (wrap
int()conversion if needed)
Key Takeaways
The outer loop decreases the starting digit from rows down to 1.
The inner loop prints from the current start i up to rows.
Total printed digits follow the triangular number count: n(n+1)/2.
This pattern combines a descending outer loop with an ascending inner loop.
❓ Frequently Asked Questions
rows, so you print more digits each time.print(j, end="") with print(j, end=" "). For neat formatting, consider fixed-width formatting.i to rows.Explore More Python Number Patterns!
Keep going to discover more number pattern programs and strengthen your loop skills.
Patterns that print 1+2+…+n digits are tied to triangular numbers. That’s why many nested-loop patterns have O(n²) output size.
12 people found this page helpful
