Alternate Ascending/Descending Number Triangle in Python

What You’ll Learn
How to print an alternate ascending/descending number triangle in Python using nested loops and an if condition. Odd rows print 1..i and even rows print i..1.
This pattern is a neat way to practice mixing nested loops with conditionals.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
12345
4321
123
21
1Complete Python Program
Count down the row length from rows to 1. Print ascending when i is odd and descending when i is even.
rows = 5
for i in range(rows, 0, -1):
if i % 2 == 0:
for j in range(i, 0, -1):
print(j, end="")
else:
for j in range(1, i + 1):
print(j, end="")
print()🧠 How It Works
Choose the row count
rows = 5 sets the maximum row length.
Outer loop (row length)
for i in range(rows, 0, -1) sets the row length: 5, 4, 3, 2, 1.
Condition decides direction
If i is even, print descending i..1. If i is odd, print ascending 1..i.
Inner loop prints the row
Two different inner loops are used depending on parity, both printing without newlines using end="".
Alternate-direction 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(rows, 0, -1):
if i % 2 == 0:
for j in range(i, 0, -1):
print(j, end="")
else:
for j in range(1, i + 1):
print(j, end="")
print()💡 Tips for Enhancement
Try These
- Validate input (reject
rows < 1) before printing the pattern - Add spaces between numbers for readability with
end=" " - Swap the parity rule to start with a descending row first
- Right-align the triangle by printing leading spaces before each row
- Try the same idea with alphabets to alternate A.. and ..A directions
Avoid
- Forgetting
print()between rows - Using the wrong
range()step when counting down - Mixing up even/odd conditions (double-check parity)
- Assuming user input is always valid (wrap
int()conversion if needed)
Key Takeaways
The outer loop controls the row length from rows down to 1.
A simple parity check (i % 2) decides whether the row is ascending or descending.
Two inner loops implement the two directions: 1..i and i..1.
Total digits printed follow the triangular number count: n(n+1)/2.
❓ Frequently Asked Questions
i is even or odd, and then chooses a descending or ascending loop accordingly.print(j, end="") to print(j, end=" "). For alignment, you may want fixed-width formatting.Explore More Python Number Patterns!
Keep going to discover more number pattern programs and strengthen your loop skills.
Mixing parity checks with nested loops is a common trick in pattern printing. It lets you change direction, spacing, or symbols on alternating rows with just one extra condition.
12 people found this page helpful
