Editor

Python Program to Print a Chessboard Pattern

Beginner · Patterns

A chessboard has 8 rows and 8 columns of squares that alternate between light and dark, so no two squares side by side have the same colour. This program draws one with characters using a simple rule: a square is light when its row number plus its column number is even, and dark when the sum is odd.

Program

chessboard_pattern.py
size = 8 # a chessboard has 8 rows and 8 columns
for row in range(size):
for col in range(size):
# Light squares where row + col is even, dark where it is odd
if (row + col) % 2 == 0:
print(".", end=" ") # light square
else:
print("#", end=" ") # dark square
print() # move to the next row
Output
. # . # . # . # 
# . # . # . # . 
. # . # . # . # 
# . # . # . # . 
. # . # . # . # 
# . # . # . # . 
. # . # . # . # 
# . # . # . # .

How it works

  1. The outer loop goes through the 8 rows and the inner loop through the 8 squares of each row, with both counting from 0.
  2. Moving one square right or one square down changes row + col by 1, which flips it between even and odd, so neighbouring squares always differ.
  3. (row + col) % 2 == 0 is true for even sums, which get a light square ., while odd sums get a dark square #.
  4. This rule makes the top-left and bottom-right corners light, just like a real chessboard.
  5. Each character is followed by a space so the board looks square rather than squashed.

Other ways to write it

Using block characters

Using block characters
size = 8
light = " " # two spaces
dark = "██" # two solid blocks
for row in range(size):
line = ""
for col in range(size):
line += light if (row + col) % 2 == 0 else dark
print(line)
Output
  ██  ██  ██  ██
██  ██  ██  ██  
  ██  ██  ██  ██
██  ██  ██  ██  
  ██  ██  ██  ██
██  ██  ██  ██  
  ██  ██  ██  ██
██  ██  ██  ██

Each square is two characters wide, which makes it roughly as wide as it is tall on screen, and light if ... else dark picks one of the two strings in a single line.

Using string repetition

Using string repetition
size = 8
even_row = ". # " * (size // 2) # starts with a light square
odd_row = "# . " * (size // 2) # starts with a dark square
for row in range(size):
if row % 2 == 0:
print(even_row)
else:
print(odd_row)
Output
. # . # . # . # 
# . # . # . # . 
. # . # . # . # 
# . # . # . # . 
. # . # . # . # 
# . # . # . # . 
. # . # . # . # 
# . # . # . # .

A chessboard has only two kinds of row, so each is built once and the two are printed in turn; this needs an even size.

Try it yourself

Use X for the dark squares and O for the light ones, and change size to 4 for a small board.

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