0
votes

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?

2
number will never be equal to "1", 2", and "3" at the same time. - Kirk Strauser
That's why, from the answer which had the correct code: while number!= "1" and number != "2" and number != "3": I don't understand why it's and not or. - Mikasa Ackerman
Draw a number line, and highlight everything other than 1. Now highlight everything other than 2, and then highlight everything other than 3. The expression you used will execute the loop when any of its conditions are true (due to the or operator), and, as you can see, the entire number line will end up executing the loop in some way. - TigerhawkT3
De Morgan's law states that "not (A and B)" is the same as "(not A) or (not B)", and "not (A or B)" is the same as "(not A) and (not B)". You used (not A) or (not B) expecting it to mean the same thing as not (A or B). - TigerhawkT3
Ahh okay thanks :3 That's a bit confusing to wrap my head round lol. - Mikasa Ackerman

2 Answers

3
votes

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.

1
votes

As mentioned, you used or instead of and. But the in operator may be a better choice:

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