error UnboundLocalError:赋值之前引用了局部变量“currentpl”:

2024-09-30 04:35:55 发布

您现在位置: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 == 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"

我该怎么解决这个问题?谢谢你的帮助!在


Tags: 代码returnif错误sqcolnumplayer
1条回答
网友
1楼 · 发布于 2024-09-30 04:35:55

user_choice不是0或1时会发生什么?在

如果user_choice不是1或0,则执行currentpl = 1或{}行的网络。这意味着currentpl是“未分配的”—它确实不存在。当你到达一个像

if currentpl == 1:

因为currentpl还不存在-它是未分配的。在

这是不允许的-您需要考虑到user_choce不是0或1的情况,方法是:

^{pr2}$

在最后一个elif子句之后。在

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

相关问题 更多 >

    热门问题