In your code, you want to break out of your loop if the user enters either x
or y
. You could write that condition (when you want to quit) as var == 'x' or var == 'y'
. But you're testing the values in a while loop, which will keep on looping if its condition true. You stop looping if the condition is false. So you'd need to negate the condition. You could use not (var == 'x' or var == 'y')
.
The version in your working code is just a more concise way of checking the same thing. By DeMorgan's laws, the negation of an disjunction (an or
expression) is the conjunction of the negations (an and
expression with negations within it). A way of writing that symbolically is: not (A or B) = not A and not B
In Python code, we can take an extra step of combining not
and ==
into !=
. But it could work without that, if you needed it to. These three loops would all work for you:
while not (var == 'x' or var == 'y'):
while not var == 'x' and not var == 'y':
while var != 'x' and var != 'y':
Pick whichever one seems most expressive to you. I'd probably prefer the third. Or I'd rewrite the condition as var not in ['x', 'y']
, to avoid the repetition of var ==
outright.