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
. # . # . # . # # . # . # . # . . # . # . # . # # . # . # . # . . # . # . # . # # . # . # . # . . # . # . # . # # . # . # . # .
How it works
- The outer loop goes through the 8 rows and the inner loop through the 8 squares of each row, with both counting from 0.
- Moving one square right or one square down changes
row + colby 1, which flips it between even and odd, so neighbouring squares always differ. (row + col) % 2 == 0is true for even sums, which get a light square., while odd sums get a dark square#.- This rule makes the top-left and bottom-right corners light, just like a real chessboard.
- Each character is followed by a space so the board looks square rather than squashed.
Other ways to write it
Using block characters
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
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
. # . # . # . # # . # . # . # . . # . # . # . # # . # . # . # . . # . # . # . # # . # . # . # . . # . # . # . # # . # . # . # .
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises