Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

python - While loops, comparing more than one value

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. ")

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...

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...