Alternating 1 and 0 Triangle in Python

What You’ll Learn
How to print an alternating 1 and 0 pattern in Python where odd rows contain 1s and even rows contain 0s.
The pattern uses modulo (i % 2) and a decreasing inner-loop range to shorten each row.
⭐ Pattern Output
For 5 rows, the pattern looks like this:
11111
0000
111
00
1Complete Python Program
Row i prints i % 2 repeatedly. The inner loop range gets smaller each row.
rows = 5
for i in range(1, rows + 1):
for _ in range(i, rows + 1):
print(i % 2, end="")
print()🧠 How It Works
Choose the number of rows
rows = 5 controls the triangle height and the first row width.
Outer loop (rows)
for i in range(1, rows + 1) iterates row by row.
Inner loop (decreasing width)
for _ in range(i, rows + 1) prints 5 digits on row 1, then 4, 3, 2, and 1.
Modulo decides 1 or 0
i % 2 is 1 for odd rows and 0 for even rows, so the rows alternate automatically.
Alternating rows
Total printed digits are 1+2+…+n = n(n+1)/2, so runtime is O(n²) for n rows.
Variation — User Input Version
Let the user choose how many rows to print:
rows = int(input("Enter the number of rows: "))
for i in range(1, rows + 1):
for _ in range(i, rows + 1):
print(i % 2, end="")
print()💡 Tips for Enhancement
Try These
- Validate input (reject
rows < 1) before printing - Flip the pattern by printing
1 - (i % 2) - Add spaces between digits for readability
- Center-align the triangle by printing leading spaces
- Turn it into a checkerboard by alternating per column too (use
(i + j) % 2)
Avoid
- Forgetting
print()after each row - Hardcoding row counts (use
rowsvariable) - Confusing
%with division (it gives remainder) - Assuming user input is always valid (wrap
int()if needed)
Key Takeaways
i % 2 is an easy way to alternate between 1 and 0 by row.
The inner loop range controls the decreasing row length.
You can flip the output by printing 1 - (i % 2).
Total prints follow n(n+1)/2, so runtime is O(n²).
❓ Frequently Asked Questions
i % 2 alternates between 1 (odd i) and 0 (even i).print(i % 2, end=" ").1 - (i % 2) instead of i % 2.Explore More Python Number Patterns!
From pyramids to Floyd’s triangle and beyond—practice nested loops with progressively richer patterns.
The modulo operator % is commonly used for pattern problems because it’s a simple way to alternate states (odd/even, on/off, 1/0).
12 people found this page helpful
