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

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

尝试查找这个,但没有人遇到过全局变量的这个问题。出于某种原因,如果我不将 global turn 放入函数中,它会一直给我这个错误。

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

This article 可能对您有所帮助。本质上,由于 python 的变量作用域,您无法访问函数外部的变量。编译器需要一个名为 turn 的局部变量(在函数体内)。

如果找不到它,就会抛出您描述的错误。因此,如果您需要引用该变量,您可以按照您的建议指定 global turn,或者您可以将变量 turn 传递给函数。

您需要指定您将使用“全局”turn 变量,这将起作用:

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