UnboundLocalError: 在赋值前引用了局部变量 'turn' - python

问题描述 投票:0回答:1

试着查了一下,但没有人对全局变量有这个问题。出于某种原因,如果我不在函数中加入全局的turn,它一直给我这个错误。

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

python processing
1个回答
1
投票

你需要指定你将使用 "全局 "变量。turn 变量,这样就可以了。

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

1
投票

这条 可能会对你有所帮助。本质上,由于python的变量作用域,你不能访问函数之外的变量。编译器希望在函数体内部有一个名为 turn.

当它没有找到它时,就会抛出你描述的错误。因此,如果你需要引用那个变量,你可以指定使用 global turn 如你所建议的,或者你可以将变量 turn 到函数中。

© www.soinside.com 2019 - 2024. All rights reserved.