Decreasing Length Number Triangle in Python

What You’ll Learn
How to print a decreasing-length number triangle in Python where each new row contains one fewer number, while values continue sequentially from 1 up to 15.
This pattern is useful for learning how the inner loop range controls how many values are printed per row.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1 2 3 4 5
6 7 8 9
10 11 12
13 14
15Complete Python Program
Use a counter k that increments for each printed value. The inner loop prints fewer items as the row index increases.
rows = 5
k = 0
for i in range(1, rows + 1):
for _ in range(i, rows + 1):
k += 1
print(f"{k:2d}", end=" ")
print()🧠 How It Works
Initialize the counter
k = 0 tracks the next number to print.
Outer loop (rows)
for i in range(1, rows + 1) iterates row by row from 1 to rows.
Inner loop (decreasing length)
for _ in range(i, rows + 1) prints fewer values as i grows: 5 values on row 1, then 4, 3, 2, and 1.
Increment and print
Each inner-loop iteration increments k and prints it using f"{k:2d}" to keep spacing tidy.
Decreasing-length triangle
Total printed values are 1+2+…+n = n(n+1)/2, so time complexity is O(n²) for n rows.
Variation — User Input Version
Let the user choose the number of rows at runtime:
rows = int(input("Enter the number of rows: "))
k = 0
for i in range(1, rows + 1):
for _ in range(i, rows + 1):
k += 1
print(f"{k:2d}", end=" ")
print()💡 Tips for Enhancement
Try These
- Validate input (reject
rows < 1) before printing - Start from a different number by initializing
ktostart - 1 - Use fixed-width printing (
{k:3d}) if values get larger - Print the same numbers in an increasing-length triangle by swapping the inner range
- Center-align the triangle by adding leading spaces per row
Avoid
- Forgetting
print()after each row - Changing the counter inside the outer loop (it must keep running)
- Using inconsistent spacing (alignment will look jagged)
- Assuming user input is always valid (wrap
int()if needed)
Key Takeaways
The outer loop decides the row number.
The inner loop prints fewer values on each next row.
A running counter k keeps the numbers continuous across rows.
Total printed values are n(n+1)/2, giving O(n²) time.
❓ Frequently Asked Questions
for _ in range(1, i + 1) so rows grow from 1 up to rows.Explore More Python Number Patterns!
From pyramids to Floyd’s triangle and beyond—practice nested loops with progressively richer patterns.
The number of values printed is a triangular number. With 5 rows, that’s 15—which is also the last value printed.
12 people found this page helpful
