I have the following piece of code that presented below with tic-tac-toe implementation. As far as I understand variable "player" is global one and it's value 'X' should be accessed from any place of the program.
board = [['_' for x in range(3)] for y in range(3)]
player = 'X'
def print_board():
for row in board:
print(row)
def check_win():
for i in range(3):
if board[i][0] == board[i][1] == board[i][2] != '_':
return board[i][0]
if board[0][i] == board[1][i] == board[2][i] != '_':
return board[0][i]
if board[0][0] == board[1][1] == board[2][2] != '_':
return board[0][0]
if board[0][2] == board[1][1] == board[2][0] != '_':
return board[0][2]
return None
def greet():
while True:
print_board()
print(f"Player {player}, make your move (row column): ")
row, col = map(int, input().split())
if board[row][col] != '_':
print("Invalid move, try again.")
continue
board[row][col] = player
winner = check_win()
if winner:
print_board()
print(f"Player {winner} wins!")
break
if "_" not in [cell for row in board for cell in row]:
print_board()
print("Tie!")
break
player = 'X' if player == 'O' else 'O'
greet()
But as a result I got the error: print(f"Player {player}, make your move (row column): ") UnboundLocalError: local variable 'player' referenced before assignment
. How to declare global variables in a correct way in Python?
What I'm doing wrong?
I expected the code of tic-tac-toe working correctly but it didn't. To resolve the issue I tried to change "player" scope and moved an assignment inside greet() method before infinite loop. It works perfect, but I have no clue why it didn't work before, as a global variable.