Home › Code Lab › Tic-Tac-Toe Game in Python
Tic-Tac-Toe in Python — two-player game, code and logic
Play a two-player Tic-Tac-Toe game in Python inside your browser, then copy, download or study how the win check works. · Level: Beginner · इसे Hindi में पढ़ें
Run the Python code
Output
How the logic works (free)
- board is a list of 9 cells. Index 0 to 8 maps to the cells 1 to 9 that the player types.
- show_board() slices the list into three rows of three and prints them with separators.
- find_winner() checks 8 possible lines (3 rows, 3 columns, 2 diagonals). If three cells in a line match and are not empty, that symbol wins.
- The while loop runs at most 9 moves. Invalid input (not 1-9, or a taken cell) prints a message and continues without using a turn.
- player switches between X and O with a single conditional expression at the end of each valid move.
- If the loop finishes 9 moves without a winner, the program prints the draw message.
Concepts you practise
- list indexing and slicing
- nested tuples for lines
- functions
- while loop with counter
- conditional switching
Full code (plain text)
board = [" "] * 9
def show_board():
for row in range(3):
cells = board[row * 3:row * 3 + 3]
print(" " + " | ".join(cells))
if row < 2:
print("---+---+---")
def find_winner():
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)]
for a, b, c in lines:
if board[a] != " " and board[a] == board[b] == board[c]:
return board[a]
return None
def play():
player = "X"
moves = 0
show_board()
while moves < 9:
choice = input(f"Player {player}, pick a cell (1-9): ")
if not choice.isdigit() or not 1 <= int(choice) <= 9:
print("Enter a number from 1 to 9.")
continue
index = int(choice) - 1
if board[index] != " ":
print("That cell is already taken.")
continue
board[index] = player
moves += 1
show_board()
winner = find_winner()
if winner:
print(f"Player {winner} wins!")
return
player = "O" if player == "X" else "X"
print("It's a draw!")
play()
Practice on PyDebug
After playing, turn the idea into a debugging habit with these free exercises: