UnboundLocalError:分配前已引用局部变量“(Var)”

时间:2018-10-20 11:32:25

标签: python variables reference local unassigned-variable

这是我的代码,很抱歉,它是瑞典语,但基本上是石头,纸,剪刀。 即使输入正确,我也会收到错误UnboundLocalError: local variable 'Answer' referenced before assignment,应该分配变量。

输入必须是石头,纸张或剪刀,否则输入将重新开始。但是即使输入正确,它也会说“ Answer”未分配。请帮助,已经在这个问题上停留了一段时间。而且global也不是一种选择,因为它必须在每个回合中都是随机的。

def Start():
    global win
    global lost
    game = input("Skriv sten, sax eller påse: ")
    game2 = game.lower()
    notright = game2 is "sten" or "sax" or "påse"
    if game2 == "quit":
        quit
    if notright == True:
        Answer = random.randint(0,3)
        if Answer == 1:
            print ("Du valde",game2,"och Jag valde Sten")
        elif Answer == 2:
            print("Du valde",game2,"och Jag valde Sax")
        elif Answer == 3:
            print("Du valde",game2,"och Jag valde Påse")
    elif notright == False:
        print("Du måste välja sten, sax eller påse. Prova igen!")
        Start()
    if Answer == 1 and game2 == "sten":
        print("Det blir oavgjort")
    elif Answer == 1 and game2 == "sax":
        lost = True
    elif Answer == 1 and game2 == "påse":
        win = True
    elif Answer == 2 and game2 == "sten":
        win = True
    elif Answer == 2 and game2 == "sax":
        print("Det blir oavgjort")
    elif Answer == 2 and game2 == "påse":
        lost = True
    elif Answer == 3 and game2 == "sten":
        lost = True
    elif Answer == 3 and game2 == "sax":
        win = True
    elif Answer == 3 and game2 == "påse":
        print("Det blir Oavgjort")

1 个答案:

答案 0 :(得分:0)

您没有循环,所以当您点击时:

elif notright == False:

您致电Start。首先quit不执行任何操作,而仅检查notright来检查if notright:是否为False。

因此循环的开始将是:

def Start():
    while True:
        game = input("Skriv sten, sax eller påse: ")
        game2 = game.lower()
        notright = game2 == "sten" or game2 == "sax" or game2 == "påse"
        if game2 == "quit":
            break
        if !notright:
            print("Du måste välja sten, sax eller påse. Prova igen!")
            continue

        Answer = random.randint(0,3)
        if Answer == 1:
            print ("Du valde" + game2 + " och Jag valde Sten")
        elif Answer == 2:
            print("Du valde" + game2 + "och Jag valde Sax")
        elif Answer == 3:
            print("Du valde" + game2 + "och Jag valde Påse")