简体   繁体   中英

UnboundLocalError: local variable 'turn' referenced before assignment - python

tried looking this up but no one had this issue for a global variable. for some reason, it keeps giving me this error if I don't put global turn inside of the function.

global turn
turn = 1
def turn_changer():
    if turn == 1:
        turn = 2
    else:
        turn = 1

This article may be helpful for you. Essentially, you cannot access variables outside of a function because of python's variable scoping. The compiler is expecting a local variable (inside the function body) named turn .

When it doesn't find it, it throws the error you describe. So if you need to reference that variable, you can either specify global turn as you suggest, or you can pass the variable turn into the function.

You need to specify that you will use the 'global' turn variable, this will work:

turn = 1
def turn_changer():
    global turn
    if turn == 1:
        turn = 2
    else:
        turn = 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM