Python 错误取消绑定LocalError:局部变量';当前PL&x27;分配前参考:

Python 错误取消绑定LocalError:局部变量';当前PL&x27;分配前参考:,python,Python,以下代码给出了UnboundLocalError错误:赋值前引用的局部变量“currentpl”: def play(num_sq, user_choice): drawStrip(num_sq) if user_choice == 0: currentpl = 1 elif user_choice == 1: currentpl = 2 while gameover(num_sq): if currentpl ==

以下代码给出了UnboundLocalError错误:赋值前引用的局部变量“currentpl”:

def play(num_sq, user_choice):
    drawStrip(num_sq)
    if user_choice == 0:
        currentpl = 1
    elif user_choice == 1:
        currentpl = 2
    while gameover(num_sq):
        if currentpl == 1:
            pick = getPlayerPick(num_sq)
            while not validPlay(pick, num_sq):
                pick = getPlayerPick(num_sq)
            makePlay(pick, player_col[currentpl])
        if currentpl == 2:
            pick = computerSelection(num_sq)
            makePlay(pick, player_col[currentpl])
        currentpl = togglePlayer(currentpl)
    if currentpl == 2:
        return "User"
    return "Computer"

我怎样才能解决这个问题?谢谢你的帮助

用户选择
不是0或1时会发生什么

如果
user\u choice
不是1或0,则执行
currentpl=1
currentpl=2
行中的另一行。这意味着
currentpl
是“未分配的”-它实际上不存在。这会在您到达以下位置时引发问题:

if currentpl == 1:
因为
currentpl
还不存在-它是未分配的

这是不允许的-您需要考虑到
user\u choce
不是0或1的情况,例如:

else:
    currentpl=10
在最后一个
elif
子句之后


另一种方法是确保在本节之前执行的代码中,
user\u choice
始终等于0或等于1,在这种情况下,您可以确保在需要测试其值之前分配(存在)了
currentpl

对不起,stewart,我对这有点陌生,所以我不明白你是什么saying@deedee别担心-我试图在上面阐明我的答案stewart你能用你的建议重新表述代码吗?因为它从我的末端不起作用Nevermind stewart,我已经修复了它,谢谢你的帮助…我所做的只是将它初始化为0,然后添加1和2