4. Simple Errors


#1

Hi. I understand everything for this part except the condition of the while loop. I understand that to get the ideal outcome the condition should be:

while choice != 'y' and choice != 'n';

what I don't understand here is that from the logic sense, why shouldn't we use "or" instead of "and" here? Thank you!


#2

Because or is short-circuiting, whereas and is not (on True). If we use or and assuming choice does not equal "y", != 'y' is sufficient to yield True from the expression, without even evaluating the other operand. This is what is meant by short circuiting.


#3

I encountered similar situations in a lot of practices later. Thank you for the great explanation!


#4

Short-circuiting or not, the result is the same, that's why short-circuiting exists, because testing the rest would make no difference to the result of the expression. (Both and and or are short-circuited)

But yes, that's totally unreadable and I wouldn't write it that way. Anything with multiple NOT's in it is just.. Nope.

So I'd write:

while not (choice == 'y' or choice == 'n'):

or better yet

while choice not in 'yn':

or..

while True:
    ...stuff

    if choice == 'y' or choice == 'n':
        break

And if a condition gets really long and difficult to read, split it up into multiple expressions, assigning results to variable names that explain what's tested, and then combine those variables with and/or/not

If something looks really complicated and unreadable, then typically there's a better way to formulate it.
A comment stating the intention in natural language can help somewhat as well.