Beginner Python – Using Basic Functions
In this tutorial, we will be creating a Tic Tac Toe game using Python and basic functions. This tutorial is perfect for beginners who are just starting to learn Python and want to practice using functions.
Step 1: Setting Up the Game
First, let’s create a 3×3 grid to represent the Tic Tac Toe game. We can use a list of lists to represent the grid:
grid = [ [' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' '] ]
Step 2: Displaying the Game Board
We can create a function to display the game board using nested loops:
def display_board(): for row in grid: print('|'.join(row)) print('-' * 5)
Step 3: Taking User Input
Next, we can create a function to take user input for placing their X or O on the game board:
def get_user_input(player): row = int(input(f'Player {player}, enter row number (0-2): ')) col = int(input(f'Player {player}, enter column number (0-2): ')) return row, col
Step 4: Checking for a Winner
We can create a function to check for a winner after each move. This function will check for three in a row vertically, horizontally, and diagonally:
def check_winner(): # Check rows for row in grid: if row[0] == row[1] == row[2] and row[0] != ' ': return True # Check columns for i in range(3): if grid[0][i] == grid[1][i] == grid[2][i] and grid[0][i] != ' ': return True # Check diagonals if grid[0][0] == grid[1][1] == grid[2][2] and grid[0][0] != ' ': return True if grid[0][2] == grid[1][1] == grid[2][0] and grid[0][2] != ' ': return True return False
Step 5: Putting it All Together
Now, we can create a main function to put all the pieces together and play the game:
def play_game(): display_board() player = 'X' while True: row, col = get_user_input(player) grid[row][col] = player display_board() if check_winner(): print(f'Player {player} wins!') break if ' ' not in [cell for row in grid for cell in row]: print('It's a tie!') break player = 'O' if player == 'X' else 'X'
That’s it! You have now created a Tic Tac Toe game using Python and basic functions. Have fun playing and experimenting with the game!
What website are you using?