Alternating 1-0 Triangle in Python

What You’ll Learn
How to print an alternating 1-0 triangle in Python using nested loops and the modulo operator (%). Each row alternates digits based on parity.
This pattern is a great way to practice how parity and modulo can drive pattern output.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
01
101
0101
10101Complete Python Program
The inner loop prints j % 2, which alternates between 0 and 1 as j increases.
rows = 5
for i in range(1, rows + 1):
for j in range(i, 2 * i):
print(j % 2, end="")
print()🧠 How It Works
Pick the number of rows
rows = 5 controls the triangle height.
Outer loop (row index)
for i in range(1, rows + 1) sets how many digits each row will have.
Inner loop prints consecutive j values
for j in range(i, 2 * i) generates i consecutive numbers, which makes each row longer than the previous.
Modulo gives 0/1 alternation
j % 2 is 0 for even numbers and 1 for odd numbers, so the output alternates as j increments.
Alternating 1-0 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(1, rows + 1):
for j in range(i, 2 * i):
print(j % 2, end="")
print()💡 Tips for Enhancement
Try These
- Validate input (reject
rows < 1) before printing the pattern - Swap
j % 2to(j + 1) % 2to flip starting digits - Print spaces between digits to make the triangle more readable
- Try the same idea with
j % 3to cycle digits 0-1-2 - Build the row as a string and print once for performance on large rows
Avoid
- Forgetting
print()between rows - Mixing up the inner loop range (it must produce i digits)
- Assuming user input is always valid
- Using
print()inside large loops without considering output cost
Key Takeaways
The inner loop prints j % 2, which alternates 0 and 1.
The range range(i, 2*i) prints exactly i digits per row.
Modulo-based patterns are a simple way to generate repeating sequences.
Total digits printed follow the triangular number count: n(n+1)/2.
❓ Frequently Asked Questions
j % 2 = 0.(j + 1) % 2 instead of j % 2 to flip 0 and 1.end="" to end=" ". If you want no trailing space, build the row and join it.Explore More Python Number Patterns!
Keep going to discover more number pattern programs and strengthen your loop skills.
Modulo arithmetic is widely used in programming—from alternating patterns and cyclic buffers to hashing. In pattern printing, it’s one of the simplest ways to repeat and alternate output.
12 people found this page helpful
