while循环,比较多个值

While loops, comparing more than one value

我可以理解如何完美地使用 while 循环,如果只是将它与一个事物进行比较,例如:

x=int(input("Guess my number 1-10"))
while x!=7: 
    print("Wrong!")
    x=int(input("Try again: "))
print("Correct it is 7. ")

但是,如果我想通过 while 循环比较两个或多个值(特别是如果我想验证某些东西),我会这样做:

number=input("Would you like to eat 1. cake 2. chocolate 3. sweets: ")
while number!= "1" or number != "2" or number != "3":
    number=input("Please input a choice [1,2,3]")
#Some code...

number 等于 1、2 或 3 时,程序应该继续...但它不会,无论我输入什么值,程序都会卡在无限循环处2-3。我也试过 while number != "1" or "2" or "3" 并且同样的无限循环也发生了。当我尝试用 and 替换所有 or 时,while 循环只会在 number 等于第一个比较值(在本例中为 "1")时中断。

有什么办法可以解决这个问题吗?

如果您有条件 number != '1' or number != '2',其中一个条件将始终为真,因此它永远不会跳出循环。请尝试 while number not in ('1', '2', '3')

如前所述,您使用了 or 而不是 and。但 in 运算符可能是更好的选择:

number=input("Would you like to eat 1. cake 2. chocolate 3. sweets: ")
while number not in ("1", "2","3"):
    number=input("Please input a choice [1,2,3]")