I've been learning python for the last couple days and in my book the challenge was to create a tic tac toe program. I think I have a general idea of how to do the game, but I ran into an issue in which insight would be helpful,
Heres the relevant part of my code
board = []
for i in range(0,3):
board.append([" "," "," "]) # Fill the board
def print_board():
for i in range(0,3):
print "| ",
for k in range(0,3):
print board[i][k],
print "|\n"
print "The first player to start will be player one with X\n, the second player will be O\n"
player_one = "X"
player_two = "O"
current_player_name = "Player One"
current_player = player_one
filled_board = False
winner = False
def check_win_col(the_winner):
for i in range(0,3):
for j in range(0,3):
if board[0][i] == board[j][0] and board[0][i] != " ":
the_winner = current_player
return the_winner
while(filled_board == False):
get_row = int(raw_input("Please enter which row you would like to move to " + current_player))
get_col = int(raw_input("Please enter the col you want to move to" + current_player))
board[get_row][get_col] = current_player
print_board()
check_win_col()
if current_player == player_one:
current_player = player_two
else:
current_player = player_one
The Error
**UnboundLocalError: local variable 'the_winner' referenced before assignment**
At first, I did not understand why the line the_winner = current_player
gave me an error, then after reading some SO questions like Unbound Local Error, I realized my issue.
On my own I thought of two solutions.
My attempt
1. Make the_winner
global. This way I wouldn't have an issue with setting the winner for the winning column to the current player. The reason I don't want to do this, is because I recall people saying during my research on this error, that it is very bad practice to use the keyword global
, and thus I do not really want to use it.
2. inside the function add a parameter for the_winner
. But the problem with this idea, is that how I would access the_winner
outside of the function itself. This would create the_winner
inside the check_win_col()
local scope, and I would not be able to manipulate this outside of the function, if I for some reason needed to. Plus the idea of adding a parameter to a function for checking the column winner seems odd. It seems like its one of those functions that should just be parameter-less if you will.
Is there a better solution I am missing? Sorry if this question seems trivial.