4/19 Simple errors - Explanation on boolean operator


#1

This is the correct code for the exercise:

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

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

But i don’t quite get why it works with bool and and doesn’t with or


#2

So this is called boolean login.

X or Y at least one is true => True
X and Y both have to be true => True

The != is probably what is tripping you up here.

With an or:
choice != "y" or choice != "n". If you think about it this will always be true. If choice is “a” choice != "y" is true so it loops. If choice is “y” choice != "n" is true so it loops. If choice is “n” choice != "y" is true so it loops. Whatever you input the condition will always be true so it loops forever.

Whereas with an and:
choice != "y" and choice != "n". This will only be true if choice is neither “y” or “n”. If choice is “a” choice != "y" is true and choice != "n" is true so it loops. If choice is “y” choice != "y" is false so it doesn’t loop. If choice is “n” choice != "n" is false so it doesn’t loop. It will only loop if you don’t enter “y” and you don’t enter “n”.

It might be easier to convert the statement:
choice != "y" and choice != "n" is equivalent to not (choice == "y" or choice == "n") so it is true if your choice is not y or n.

Hope that helps :slight_smile:


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.