0

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

输入必须是石头、纸或剪刀,如果不是,则重新开始。但即使输入正确,它也会显示未分配“答案”。请帮助,已经卡在这个问题上一段时间了。不做它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")
4

1 回答 1

0

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

elif notright == False:

你打电话Start。Firstquit不做任何事情,检查 if notrightis False 也无济于事,只做if notright:.

所以循环的开始是:

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")
于 2018-10-20T11:55:12.737 回答