Creating a chess board in the Python console

Introduction – The Chess Board Challenge

One of the best ways to learn a computer language is to try and challenge yourself to create solutions to simple problems. This gets you familiar with the language, syntax and helps you develop the correct way of thinking. In many computer programming languages there a multiple ways of achieving the same thing, but I am of the view you need to first generate working code and that optimised code will follow after.

The class were given the following scenario: A chess board is made up of alternating black and white squares arranged in an 8×8 grid. Build a function that generates output that shows how the chessboard should appear.

The Function

def create_chess_board():
    board = []
    for i in range(8):
        row = []
        for j in range(8):
            if (i + j) % 2 == 0:
                row.append("white")
            else:
                row.append("black")
        board.append(row)
    return board

The class began by producing the function create_chess_board() which creates an 8×8 chess board represented as a 2-dimensional list, where each element in the list represents a square on the board. The function uses nested for loops to iterate through the rows and columns of the board. The if (i + j) % 2 == 0 check is used to determine whether the current square should be coloured white or black, based on the position of the square on the board. The resulting board is returned by the function.

You can then use the function to create a chess board and store it in a variable like this:

chess_board = create_chess_board()

You can also use print statements in your function to print the chess board on the console.

def create_chess_board():
    board = []
    for i in range(8):
        row = []
        for j in range(8):
            if (i + j) % 2 == 0:
                row.append("white")
            else:
                row.append("black")
        board.append(row)
    for i in range(8):
        for j in range(8):
            print(board[i][j],end=" ")
        print()
    return board

rather than store the chess board in a variable, I just wanted to print it out so I simple called the function

create_chess_board()

Here’s the output

Chessboard output

Conclusion

Code challenges in Python are generally fun. This exercise to create a chessboard makes you think about some nice programming concepts such as arrays and nested loops. What will you next Python Challenge be?

Our next step is to build a chessboard in Python using Turtle. – Have a look.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top