Alternating Ascending/Descending Rows in Python

What You’ll Learn
How to print a number pattern in Python where each row alternates order: odd rows print numbers in ascending order and even rows print in descending order, while keeping the numbers consecutive overall.
This pattern is a great way to practice using a running counter and a simple odd/even row check.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
3 2
4 5 6
10 9 8 7
11 12 13 14 15Complete Python Program
We keep a counter k that increases for every printed number. For even rows, we compute the row end first and print in reverse.
k = 1
for i in range(1, 6):
m = k + i - 1 # last value in this row
for _ in range(i):
if i % 2 == 1:
print(k, end=" ")
else:
print(m, end=" ")
m -= 1
k += 1
print()🧠 How It Works
Start a counter
k = 1 is the next number to be printed.
Row loop decides the length
Row i prints exactly i numbers.
Odd rows print forward
If i is odd, we print k and keep increasing it.
Even rows print backward
For even rows, we compute m = k + i - 1 (the last value in the row) and print m, m-1, ....
Zigzag rows
Total printed numbers are 1+2+…+r, so runtime is O(r²) for r rows.
Variation — User Input Version
Let the user choose the number of rows. The same logic works for any size.
rows = int(input("Enter number of rows: "))
if rows < 1:
raise ValueError("rows must be at least 1")
k = 1
for i in range(1, rows + 1):
m = k + i - 1
for _ in range(i):
if i % 2 == 1:
print(k, end=" ")
else:
print(m, end=" ")
m -= 1
k += 1
print()💡 Tips for Enhancement
Try These
- Print the pattern in a fixed-width grid with padding
- Replace numbers with letters to create an alternating alphabet pattern
- Start from 0 instead of 1 to see a different sequence
- Keep odd rows descending and even rows ascending to invert the zigzag
- Store each row in a list and reverse it for even rows (alternative approach)
Avoid
- Forgetting to compute
mbefore printing an even row - Incrementing
kin the wrong place (sequence breaks) - Using
rows < 1without validation - Printing without spaces (multi-digit numbers become unreadable)
Key Takeaways
Row i contains exactly i consecutive numbers.
Odd rows print in ascending order; even rows print in descending order.
A single counter maintains continuity across rows.
Total prints are triangular, so runtime is O(r²).
❓ Frequently Asked Questions
k and the row length is i, then the last value is k+i-1. We store it as m.Explore More Python Number Patterns!
Zigzag patterns are a stepping stone to snake-matrix and spiral problems.
This alternating-row idea is similar to how a snake traversal works in a matrix: left-to-right on one row, then right-to-left on the next.
7 people found this page helpful
