While 循环在 Python 中不起作用

问题描述 投票:0回答:3

while 循环无法正常工作。 Again 变量将指示是否再次执行 while 循环。如果again = 1,则执行while循环,程序再次运行。如果再次=0,则不会。

由于某种原因,again=1 总是,所以无论怎样,while 循环总是被执行。有人注意到代码中有错误吗?

 score = 0
 loops = 0
 again = 1
 while (again != 0):
    import random
    real = random.randint(1,9)
    fake1 = random.randint(1,9)
    fake2 = random.randint(1,9)
    comb = random.randint(1,9)
    rep = 0
    guess = 0

    if (comb == 1 or comb == 2 or comb == 3):
        print(real, fake1, fake2)
        loops += 1
        guess = int(input("Choose between these numbers"))
        if (guess == real):
            score += 1
            print ("Congrats!")
        else:
            print ("Wrong, better luck next time!")
    if (comb == 4 or comb == 5 or comb == 6):
        print (fake1, fake2, real)
        loops += 1
        guess = int(input("Choose between these numbers"))
        if (guess == real):
            score += 1
            print ("Congrats!")
        else:
            print ("Wrong, better luck next time!")

    if (comb == 7 or comb == 8 or comb == 9):
        print (fake2, real, fake1)
        loops += 1
        guess = int(input("Choose between these numbers"))
        if (guess == real):
            score += 1
            print ("Congrats!")
        else:
            print ("Wrong, better luck next time!")
    again == int(input("Do you wanna go again?"))
    print(again)
python loops while-loop
3个回答
1
投票

您在将值分配给名为 again 的变量时使用比较运算符:

again == int(input("Do you wanna go again?"))

您必须删除其中一个等号:

again = int(input("Do you wanna go again?"))

0
投票
again == int(input("Do you wanna go again?"))

这不会像你想象的那样,因为 == 意味着它正在检查这个语句是否为真。你想要一个=。


0
投票

对于此行:

again == int(input("Do you wanna go again?"))

“==”用于在比较两个值时返回 True 或 false 的布尔值。例如:

print(2 > 1)
# output: True

代码应更正为:

again = int(input("Do you wanna go again?"))
© www.soinside.com 2019 - 2024. All rights reserved.