4. Simple errors, questions about the logic?


#1



I am confused about the logic to this question, below is my code which is correct and i understand why it is correct, but my question is why the other answers i tried give me an infinite loop.


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

#other answers
#while (choice != 'y' or choice != 'n')
#while (choice != 'y' or 'n')

Again I understand the logic on the correct answer, but if you enter 'y' or 'n' on the other two answers you get an infinite loop, if you're supposed to check whether the answer is 'y' OR 'n' and the choice is infact 'y' or 'n' why does the loop still run infinitely?


#2

a while loop runs as long as the condition is true, agree?

lets first look at this one:

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

if enter something invalid, it will obviously run again. lets say i enter something valid we get:

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

make sense? Which results in:

while(false or true)

which is true, so the loop will run again (false or true is true)

so, that is why it is infinity loop.

lets look at the other one:

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

well that one is simple, strings are considered true which you can prove:

if 'n':
   print True

which means 'n' is always true, causing a infinity loop


#3

Ah, I see, thanks for the quick reply and simple explanation!

I knew it had something to do with the while reading the conditional as true, and now I understand why it does, thanks again for the reply!