Upcoming: student sessions with AI researchers, software engineers, and technology mentors.
Back to projects
PythonBeginner–Intermediate2 sessions

Tic-Tac-Toe

A classic next-step project for students who are comfortable with basic Python. It introduces board representation, functions, turns, validation, and game-winning logic without any external libraries.

Starter code

Read it. Run it. Change it.

Save the code below as tic_tac_toe.py. The example is intentionally small enough for a student to explain line by line before adding new features.

tic_tac_toe.pyPython
board = [" "] * 9

winning_lines = [
    (0, 1, 2), (3, 4, 5), (6, 7, 8),
    (0, 3, 6), (1, 4, 7), (2, 5, 8),
    (0, 4, 8), (2, 4, 6)
]

def show_board():
    print(f" {board[0]} | {board[1]} | {board[2]} ")
    print("---+---+---")
    print(f" {board[3]} | {board[4]} | {board[5]} ")
    print("---+---+---")
    print(f" {board[6]} | {board[7]} | {board[8]} ")

def has_won(player):
    return any(
        board[a] == board[b] == board[c] == player
        for a, b, c in winning_lines
    )

player = "X"
moves = 0

while moves < 9:
    show_board()
    position = int(input(f"Player {player}, choose 1-9: ")) - 1

    if position not in range(9) or board[position] != " ":
        print("That space is not available. Try again.")
        continue

    board[position] = player
    moves += 1

    if has_won(player):
        show_board()
        print("Player", player, "wins!")
        break

    player = "O" if player == "X" else "X"
else:
    show_board()
    print("It's a draw!")

How to run it on a laptop

  1. 1. Install Python 3 if it is not already available.
  2. 2. Open IDLE, Thonny, VS Code, or any simple text editor.
  3. 3. Copy the code into a new file named tic_tac_toe.py.
  4. 4. Run the file. No internet connection, database, or server is required.

Build it step by step

1

Represent the board

Use a list of nine spaces to represent the grid.

2

Draw the board

Create a function that prints the current game state.

3

Take turns

Alternate between X and O after valid moves.

4

Check winners

Test rows, columns, and diagonals after each move.

Make it your own

  • Add a simple computer opponent that chooses an empty space.
  • Add player names.
  • Create a graphical version later with Tkinter or JavaScript.