Alternating Odd/Even Rows Number Pattern in Python

What You’ll Learn
How to print an alternating odd/even rows number pattern in Python using nested loops and an if condition. Odd rows print odd numbers and even rows print even numbers.
This is a great exercise for combining conditionals with step-based ranges.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
2 4
1 3 5
2 4 6 8
1 3 5 7 9Complete Python Program
Use i % 2 to choose whether to print odd or even numbers on each row.
rows = 5
for i in range(1, rows + 1):
if i % 2 == 0:
for j in range(2, 2 * i + 1, 2):
print(j, end=" ")
else:
for j in range(1, 2 * i, 2):
print(j, end=" ")
print()🧠 How It Works
Decide the number of rows
rows = 5 prints 5 lines of output.
Outer loop picks the row index
for i in range(1, rows + 1) runs i = 1..5.
If i is even, print even numbers
For even rows, we print 2, 4, 6, ... up to 2*i using range(2, 2*i + 1, 2).
If i is odd, print odd numbers
For odd rows, we print 1, 3, 5, ... up to 2*i - 1 using range(1, 2*i, 2).
Alternating odd/even rows
A single parity check creates two different sequences per row, producing the alternating effect.
Variation — User Input Version
Let the user choose the number of rows at runtime:
rows = int(input("Enter the number of rows: "))
for i in range(1, rows + 1):
if i % 2 == 0:
for j in range(2, 2 * i + 1, 2):
print(j, end=" ")
else:
for j in range(1, 2 * i, 2):
print(j, end=" ")
print()💡 Tips for Enhancement
Try These
- Remove trailing spaces by building each row as a list and joining it
- Swap the rule so odd rows print evens and even rows print odds
- Print squares/cubes of numbers instead of raw values
- Right-align the pattern by printing leading spaces
- Use the same logic to alternate other sequences (primes, Fibonacci, etc.)
Avoid
- Forgetting the step value of 2 in the inner ranges
- Using the wrong end value in
range()(stop is exclusive) - Assuming user input is always valid
- Mixing up the even/odd branch logic
Key Takeaways
A parity check (i % 2) decides which sequence to print.
Even rows print evens up to 2*i; odd rows print odds up to 2*i - 1.
Step-based ranges (step=2) make odd/even sequences easy.
This is a simple example of combining conditionals with nested loops.
❓ Frequently Asked Questions
end=" " to print a space after each value. You can remove trailing spaces by joining a list instead.end=" " to end="". For readability, spaces are usually better.Explore More Python Number Patterns!
From simple triangles to alternating sequences—keep practicing nested loops and conditionals.
Odd and even sequences can be generated without conditionals by choosing the right range(): odds use range(1, n, 2) and evens use range(2, n, 2).
12 people found this page helpful
