Simple errors Why AND and not OR


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

how come the boolean (and) works but if i use (or) it wont.

False and False is False
False or False is False

It seems that the logic is the same for both in the condition created in the above code.


You're assuming that both expressions always evaluate to False, they are probably meant to occasionally evaluate to True as well.


This was confusing me too, but I think I understand it now.

"While variable is false and variable is false do the following action" means that once one of the variables is true, it will not longer execute that piece of code in the while loop because both criteria are not met.

"While variable is false or variable is false do the following action" means that the variable in either condition can be true, but if the other one is false then the code will still be executed. Because it is impossible for the same variable to be true in the "or" comparison, you get stuck in a loop.

Hope that made sense!


ok it goes like this ' while' checks for the limit until which the condition given is true so when the condition is choice != "y" and choice != "n" python will keep performing until it gets a input in which y or n is present however if you set the code to choice != "y" or choice != "n" and then you enter ' y ' then it won't be equal to ' n ' and the python will detect that and again print the sorry statement.
when you answer it as ' n ' then python will detect the input is not equal to ' y ' and again printing the sorry statement.

but when you use and python wants both the conditions satisfied on both sides of and so if you enter y or n both the conditions won't be satisfied and the code will end


Thank you all for you input it was and :slight_smile: is really helpful. i found this in the archives.

while choice != 'y' and choice != 'n' :
It means that the loop will only execute while both these conditions are True, namely that the user neither entered y norn. ...
choice != 'y'

choice != 'n'
If the user entered either y or n, then we have a valid response, and can proceed.
If instead, we had ...
while choice != 'y' or choice != 'n' :
... it would mean that if either y or n had not been entered, we need a new input value. But that would be True, whether the user entered y or n, because if one of those values was entered, the other was not. The condition, taken as a whole, would always be True, so the loop would be infinite.
Let's say the user entered y. We would want the loop to terminate. choice != 'y' would be False, and that's fine. But, choice != 'n' would be True, so the whole condition would be True, and the loop would continue. The result would be similar if the user had entered n.


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