简体   繁体   English

While循环在Python中不起作用

[英]While loop not working in Python

The while loop is not working properly. while循环无法正常工作。 The again variable will dictate whether or not the while loop will be executed again. Again变量将决定是否将再次执行while循环。 If again = 1, then the while loop will be executed and the program will run again. 如果再次= 1,则将执行while循环,并且程序将再次运行。 If again =0, then it will not. 如果再次= 0,则不会。

For some reason, again=1 always, so no matter what, while loop is always being executed. 由于某种原因,再次始终为= 1,因此无论如何,总是执行while循环。 Does anyone notice an error in the code? 有人注意到代码中的错误吗?

 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)

You use a comparison operator while assigning a value into variable called again : 在将值分配给再次调用的变量时,您可以使用比较运算符:

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

You must delete one of the equals signs: 您必须删除一个等号:

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

This is not going to do what you think, because == means it is checking if this statement is true. 这不会做您想的,因为==表示它正在检查此语句是否为真。 You want to have a single =. 您想要一个=。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM