Alternating 1-0 Triangle (Starts with 1) in Python

What You’ll Learn
How to print an alternating 1-0 triangle in Python where every row starts with 1: 1, 10, 101, 1010, 10101.
This pattern is a simple exercise in using modulo to generate repeating sequences.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
10
101
1010
10101Complete Python Program
Print j % 2 for j = 1..i. This produces 1,0,1,0,... on each row.
rows = 5
for i in range(1, rows + 1):
for j in range(1, i + 1):
print(j % 2, end="")
print()🧠 How It Works
Set the number of rows
rows = 5 controls how many lines are printed.
Outer loop controls row length
for i in range(1, rows + 1) sets row length to 1, 2, 3, 4, 5.
Inner loop prints parity of j
for j in range(1, i + 1) prints j % 2, producing 1 for odd j and 0 for even j.
New line after each row
print() moves to the next row.
Alternating sequence 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(1, i + 1):
print(j % 2, end="")
print()💡 Tips for Enhancement
Try These
- Flip the pattern by printing
(j + 1) % 2instead ofj % 2 - Add spaces between digits for readability
- Use
j % kto create repeating cycles like 0-1-2 - Build each row as a string and print it once for large sizes
- Center the triangle by printing leading spaces before each row
Avoid
- Forgetting
print()between rows - Mixing up the inner loop bounds (it should run exactly i times)
- Hardcoding values if you want a reusable pattern size
- Assuming user input is always valid
Key Takeaways
Using j % 2 prints 1 for odd j and 0 for even j.
Starting j from 1 ensures every row begins with 1.
The outer loop controls row length, growing from 1 to rows.
Total digits printed follow the triangular number count: n(n+1)/2.
❓ Frequently Asked Questions
(j + 1) % 2 instead of j % 2.print(j % 2, end=" "). If you want no trailing spaces, build and join a list.Explore More Python Number Patterns!
Keep going to discover more number pattern programs and strengthen your loop skills.
Parity-based patterns show up everywhere—from chessboard coloring to toggles and bit tricks. Modulo is an easy way to express them in code.
12 people found this page helpful
