Tic Tac Toe Game in Python
In this lesson: Make a 2-player Tic Tac Toe game in Python — board, moves, win check — complete beginner code with output. In Hindi & English.
What we are building
Tic Tac Toe is a classic 3x3 game where two players take turns placing X and O, trying to get three in a row. It is a great project because it combines a board, turns, input and a winner check — all core skills. We will build it step by step.
The board
board = ["1", "2", "3",
"4", "5", "6",
"7", "8", "9"]
player = "X"
We store the 9 cells in a list. The numbers 1-9 mark empty spots and also tell the player which number to choose. A player replaces a number with X or O when they move.
Showing the board
def show(board):
print(board[0], "|", board[1], "|", board[2])
print("---------")
print(board[3], "|", board[4], "|", board[5])
print("---------")
print(board[6], "|", board[7], "|", board[8])
---------
4 | 5 | 6
---------
7 | 8 | 9
This prints the list as a 3x3 grid with lines between rows, so players can see the current state and pick a spot by its number.
Checking for a winner
wins = [
(0,1,2), (3,4,5), (6,7,8), # rows
(0,3,6), (1,4,7), (2,5,8), # columns
(0,4,8), (2,4,6) # diagonals
]
def check_winner(board):
for a, b, c in wins:
if board[a] == board[b] == board[c]:
return board[a]
return None
We list all 8 winning lines by their positions. If any line has the same mark in all three cells, that mark is the winner. We run this after every move.
The full game loop
for turn in range(9):
show(board)
spot = int(input(player + "'s move (1-9): ")) - 1
if board[spot] in ("X", "O"):
print("Taken, try again")
continue
board[spot] = player
winner = check_winner(board)
if winner:
show(board)
print(winner, "wins!")
break
player = "O" if player == "X" else "X"
else:
print("It's a draw")
The loop runs up to 9 turns. Each turn shows the board, takes a move, checks it is free, places the mark, checks for a winner, then switches players. If all 9 fill with no winner, the else prints a draw.
Common mistakes
- Off-by-one on positions. Users pick 1-9, but the list is 0-8 — subtract 1.
- Not checking if a spot is taken. Verify the cell is free before placing.
- Checking the winner before the move. Place the mark first, then check.
- Forgetting to switch players. Flip the player only after a valid move.
Summary
- Store the board as a list of 9 cells.
- Show it as a 3x3 grid so players can pick by number.
- List the 8 winning lines and check them after each move.
- Switch players with
player = "O" if player == "X" else "X". - A full board with no winner is a draw.
Next, strengthen logic with Python loops, or organise code with Python functions.
Frequently Asked Questions
How is the Tic Tac Toe board stored in Python?
How do I check who won?
How do players take turns?
player = "O" if player == "X" else "X" to flip between the two.