另一个 python 范围界定问题

Yet another python scoping issue

我已经阅读了很多范围界定帖子,但我还没有找到适合我的答案。我使用 python 2.7.6。 这是代码:

def play(A, B):
    state = START_STATE
    #player = None
    while state[1] < goal and state[2] < goal:
        if state[0]:
            player = B
        else:
            player = A
         state = resolve_state(state, player(state))
    return player

这会引发 UnboundLocalError。取消注释第 3 行的效果总是返回 None 变量,但我确信播放器变量始终是 A 或 B。将播放器设置为全局变量可以解决问题。谁能解释这种行为?从我读到的 while 和 if 语句不创建它们的范围所以函数应该是在 while/if 块中声明的变量的范围。

错误说:"UnboundLocalError: local variable 'player' referenced before assignment"

我确定循环会执行,因为 START_STATE = (0, 0, 0, 0) + 我用打印仔细检查了它 + 使播放器成为全局解决了问题并且它不影响循环入学条件

@jonathan -> 它保留了旧版本

您的代码没有遍历循环 - 下面是演示它的简化代码:

# noloop.py

def loop(A, B, x):
    #player = None
    while x:
        if True:
            player = B
        else:
            player = A
        x = False

    return player

调用和结果:

>>> import noloop
>>> noloop.loop("A", "B", True)
'B'
>>> noloop.loop("A", "B", False)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "noloop.py", line 12, in loop
    return player
UnboundLocalError: local variable 'player' referenced before assignment
>>> 

所以你的断言是错误的,点清除。请注意,您的代码依赖于两个全局变量 START_STATEgoal,这使得调试更加困难。首先重写你的函数以摆脱所有全局变量(提示:将 START_STATEgoal 作为参数传递),然后添加一些调试代码(如循环之前、内部和之后的一些打印语句),以及你可能会自己找出问题所在。