While循环,比较多个值 [英] While loops, comparing more than one value
问题描述
仅将它与一件事进行比较,我就能理解如何完美地使用while循环,例如:
I can understand how to use the while loop perfectly if just to compare it with one thing, for example:
x=int(input("Guess my number 1-10"))
while x!=7:
print("Wrong!")
x=int(input("Try again: "))
print("Correct it is 7. ")
但是,如果我想通过while循环比较两个或多个值(特别是如果我想验证某些东西),我将执行以下操作:
However, if I want to compare two or more values through while loops (especially if I want to validate something), I would do something like this:
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
时,仅当number
等于比较的第一个值(在本例中为"1"
)时,while循环才会中断.
When number
does equal 1, 2 or 3, the program should proceed... but it doesn't, no matter what value I input, the program will be stuck at an infinite loop at line 2-3. I have also tried while number != "1" or "2" or "3"
and the same infinite loops also occurs. When I try replacing all or
with and
, the while loop will only break when number
equals the first value compared (which in this case is "1"
).
有什么办法可以解决这个问题?
Is there any way that I can resolve this?
推荐答案
如果条件为number != '1' or number != '2'
,则这些条件之一将始终为true,因此它将永远不会中断.尝试使用while number not in ('1', '2', '3')
.
If you have a condition of number != '1' or number != '2'
, one of those conditions will always be true, so it'll never break out of the loop. Try while number not in ('1', '2', '3')
instead.
这篇关于While循环,比较多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!