Shifted Number Triangle in Python

What You’ll Learn
How to print a shifted number triangle in Python using nested for loops. Each new row starts from the next number and runs up to rows: 1..rows, then 2..rows, then 3..rows, and so on.
This pattern is a great exercise for learning how an inner loop can start from a variable value (the current outer-loop index).
⭐ Pattern Output
For rows = 5, the pattern looks like this:
12345
2345
345
45
5Complete Python Program
The outer loop selects the row start value. The inner loop prints from that start up to rows.
rows = 5
for i in range(1, rows + 1):
for j in range(i, rows + 1):
print(j, end="")
print()🧠 How It Works
Choose the row count
rows = 5 sets the maximum number printed on each row.
Outer loop (row start)
for i in range(1, rows + 1) picks the starting digit for each row: 1, then 2, then 3, and so on.
Inner loop (print i..rows)
for j in range(i, rows + 1) prints from the current start i up to rows using print(j, end="").
New line
print() ends the row so the next iteration starts on a fresh line.
Shifted number triangle
Total digits printed: 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, rows + 1):
print(j, end="")
print()💡 Tips for Enhancement
Try These
- Validate input (reject
rows < 1) before printing - Add spaces between numbers with
print(j, end=" ") - Print the inverse version by swapping the ranges
- Convert the pattern to an ascending triangle by changing the inner loop start/end
- Try an alphabet version by printing
chr(64 + j)forjin the same loop
Avoid
- Forgetting
print()between rows - Mixing up
range()endpoints (remember the stop value is exclusive) - Assuming user input is always valid (wrap
int()conversion if needed) - Hardcoding values when you want a reusable pattern function
Key Takeaways
Row i starts printing from i and ends at rows.
The inner loop starts at a variable value (i), which creates the shifting effect.
Total printed digits follow the triangular number count: n(n+1)/2.
The same idea works for star patterns and alphabet patterns.
❓ Frequently Asked Questions
1..5, then 2..5, then 3..5, and so on.print(j, end="") with print(j, end=" "). If you want clean alignment, consider formatting with fixed width.rows to the desired maximum. The last row will always print just that number.Explore More Python Number Patterns!
Keep going to discover more number pattern programs and strengthen your loop skills.
The total digits printed here still form a triangular number: 1+2+…+n = n(n+1)/2. That’s why these loop-based patterns often have O(n²) output size.
12 people found this page helpful
