'Python and vs or in while loop

choice = input('Enjoying the course? (y/n)')

while choice != "y" or choice != "n":
  choice = input("Sorry, I didn't catch that. Enter again: ")

im trying to understand why the code above doesnt exit the while loop if i input 'y' or 'n', but if i change the or to and and input 'y' or 'n' the while loop exits? To my understanding it should have worked both.

In or case its read as

while choice is not 'y' or choice is not 'n' -> exit

just like and

while choice is not 'y' and choice is not 'n' -> exit



Solution 1:[1]

You should use and instead of or:

while choice != "y" and choice != "n":
  choice = input("Sorry, I didn't catch that. Enter again: ")

choice != "y" or choice != "n" always evaluates to True since choice cannot be y and n at the same time.

Solution 2:[2]

while choice != "y" or choice != "n":
    choice = input("Sorry, I didn't catch that. Enter again: ")

You want the while loop to repeat

until choice equals "y" or choice equals "n"

So you want it to last

while choice doesn't equal "y" and choice doesn't equal "n"

So the correct code in your case would be

while choice != "y" and choice != "n":

Note


In Python a better practice would be writing this

while choice not in ("y", "n"): # Easier to understand, right?

Solution 3:[3]

Look at it this way: if you enter "y" on or operator below happens

while "y" != "y" or "y" != "n":

which translates to below

while False or True:

and its or operator so (True or False) will always be True

if you enter "y" on and operator below happens

while "y" != "y" and "y" != "n":

which translates to below

while False and True:

and as its and operator so (True and False) will always be False

hence you should use and if you want to leave the loop

Solution 4:[4]

There are exactly 3 cases:

  • source is 'x'
  • source is 'y'
  • source is something else. Not one of {'x', 'y'}.

In all of these 3 states the OR condition holds, and therefore the loop continues. In other words, the condition is always True, because choice can be only one of the two values. And therefore it is always not one of them, at least. Hence, the OR condition always holds, and the loop continues.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 VMSMani
Solution 4 Doron Cohen