How To Program A Tic Tac Toe Board In Python

In this tutorial, we will learn how to create a simple Tic Tac Toe game using Python. This classic game consists of a 3×3 grid where players take turns to place their symbols (typically ‘X’ and ‘O’) until one player has their symbols in an uninterrupted line (horizontally, vertically, or diagonally) or the board is completely filled, resulting in a draw.

We will create a program that consists of functions for:
– Displaying the Tic Tac Toe board
– Taking turns for player moves
– Checking if a player has won or the game has ended in a draw

Note: This tutorial assumes you have a basic understanding of Python programming.

Step 1: Creating the Tic Tac Toe Board

We’ll create a function that initializes a 3×3 grid to represent the Tic Tac Toe board. The grid is represented as a list of lists, with each list representing a row on the board.

Step 2: Displaying the Tic Tac Toe Board

Next, we’ll create a function to display the Tic Tac Toe board in a user-friendly format. The board is printed with row and column separators and proper formatting.

Step 3: Taking Player Turns

We need a function to handle player moves. This function takes the board, row, column and player symbol as input and updates the board. We also need to ensure the move is valid (within board bounds and not overwriting an existing symbol).

Step 4: Checking the Game Status

After each move, we need to check if the game has been won, lost or drawn. The following function takes the board and checks all horizontal, vertical, and diagonal rows for a win, or all positions filled for a draw.

Step 5: Running the Game

Finally, we’ll create a function to run the game loop. It initializes the board, displays it, and takes input from the players, making a move, checking for a win or draw, and switching turns.

Full Code:


In this tutorial, we learned how to create a simple Tic Tac Toe game in Python. By following these steps and understanding the functions, you can further optimize the code and implement additional features, such as a more intelligent computer player or improved user input validation. Enjoy playing and building upon your new Tic Tac Toe game!