Simple Errors - Simple Question


I wrote the code using

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

instead of

while (choice != 'y') and (choice != 'n'):

It kept taking me through a infinite loop. Why did this happen? What is the main difference taking place between and & or?

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

while (choice != 'y') and (choice != 'n'):  # Fill in the condition (before the colon)
    choice = raw_input("Sorry, I didn't catch that. Enter again: ")


A loop will run as long as the condition is True. The moment the condition is met (aka false), the loops exits. Agree?

if you use or, if the user enters something invalid (for example x, both conditions are true, so, the condition is true, so the loop continues. If the user enters y or n (doesn't matter) one of both is true, the other is false. true or false results in true, so the loops keep running.

now lets look at and. if the the user enters something invalid (for example x), both conditions are true, so the loop is true, so will continue running. If the user enters something valid, one of the condition will be false, the other will be true. True and false results in false, the loops exit because the user ends something valid

Hope this explains the infinity loop (and i hope i got it right, always tricky to explain this)


You moderators are really great at your job. Thank you very much for the explanation.