0

I have a global variable at the top of my .py file. When I tell my function to do some action on it, the interpreter gives me a statement that suggests that I am talking about a local variable that has been not established.

I'm using Python 3.7.3 and Win 10. The program is supposed to be a Tic Tac Toe game played in console.

Basically, I am lost. The variable is clearly defined, the function is referring to it, yet Python does not see it. I do not know what to do, it's a very simple program and it is not working. I really do not know what to do, from what I have seen on the Net nobody, either in Google or there had a similar problem (that I am aware of, obviously).

# some other variables, all at the top of file, before anything else

turn = 1

# some functions referring to the above variables, all are working

# the function that is "blind"

def changeboard():
    if turn % 2 == 1:
        t = input (f"Where to put your {p_o_tile}, player one?")

        changetile(t, p_o_tile)
        turn += 1
    else:
        t = input(f"Where to put your {p_t_tile}, player two?")

        changetile(t, p_t_tile)
        turn += 1

The error I get:

Traceback (most recent call last):

...

File "C:\Users\Szymon Brycki\Desktop\Python Notes\TicTacToe3.py", line 85, in changeboard

if turn % 2 == 1:

UnboundLocalError: local variable 'turn' referenced before assignment

Basically, the function should rotate between players depending on if the turn counter is even or odd. The player who is currently pointed at by the function should tell the game which tile to change into an "x" or "o" Just that. It's really simple and I really cannot guess why it is not working.

  • When you do `turn += 1` you do an assignment to `turn`. That makes it a local variable. You don't want global variables anyway, so use parameters and a return value in your function. – Matthias Aug 12 '19 at 10:18
  • you need to tell your function that turn is a global variable: `global turn` – Stef Aug 12 '19 at 10:19

1 Answers1

0

Tell the function that the variable turn is global by adding the line global turn inside the function.

turn = 1

# some functions referring to the above variables, all are working

# the function that is "blind"

def changeboard():
    global turn       # <-------- mention it as global
    if turn % 2 == 1:
        t = input (f"Where to put your {p_o_tile}, player one?")

        changetile(t, p_o_tile)
        turn += 1
    else:
        t = input(f"Where to put your {p_t_tile}, player two?")

        changetile(t, p_t_tile)
        turn += 1
j23
  • 3,139
  • 1
  • 6
  • 13