Editor

Python Program to Print a 0-1 Triangle Pattern

Beginner · Patterns

A 0-1 triangle, also called a binary triangle, is a right-angled triangle filled with 0s and 1s that take turns. In this version each row starts with the opposite digit to the row above, so the digits also alternate down every column, like a chessboard.

Program

binary_triangle.py
rows = 5 # or: rows = int(input("Enter the number of rows: "))
for i in range(1, rows + 1):
for j in range(1, i + 1):
# 1 when row + column is even, 0 when it is odd
if (i + j) % 2 == 0:
print(1, end=" ")
else:
print(0, end=" ")
print() # move to the next line
Output
1 
0 1 
1 0 1 
0 1 0 1 
1 0 1 0 1

How it works

  1. Row i has i digits, numbered j from 1 to i, the same shape as a right-angled star triangle.
  2. The digit depends on whether i + j is even or odd, and moving one place right or one row down changes the sum by 1, so neighbouring digits always differ.
  3. Row 1 starts with 1 because 1 + 1 is even, row 2 starts with 0 because 2 + 1 is odd, and so on, which is why the first column alternates too.
  4. end=" " keeps a row on one line with spaces between the digits, and the empty print() ends the row.

Other ways to write it

Every row starts with 1

Every row starts with 1
rows = 5
for i in range(1, rows + 1):
for j in range(i):
print((j + 1) % 2, end=" ") # 1, 0, 1, 0, ...
print()
Output
1 
1 0 
1 0 1 
1 0 1 0 
1 0 1 0 1

(j + 1) % 2 is 1 for the first digit of each row, then 0, then 1, so every row reads 1 0 1 0 ... from the left, the other common version of this pattern.

Flipping one bit across the rows

Flipping one bit across the rows
rows = 5
bit = 1
for i in range(1, rows + 1):
for j in range(i):
print(bit, end=" ")
bit = 1 - bit # turns 1 into 0 and 0 into 1
print()
Output
1 
0 1 
0 1 0 
1 0 1 0 
1 0 1 0 1

A single bit flips from one digit to the next and carries on into the next row, like the counter in Floyd's triangle.

Try it yourself

Print * in place of 1 and a space in place of 0, and look at the pattern it makes.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises