7

In Codeacademy, I ran this simple python program:

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

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

I entered y at the console but the loop never exited

So I did it in a different way

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

while True:  # Fill in the condition (before the colon)
    if choice == 'y' or choice == 'Y' or choice == 'N' or choice == 'n':
        break
    choice = raw_input("Sorry, I didn't catch that. Enter again: ")

and this seems to work. No clue as to why

1
  • 3
    Hint: can you name a value of choice where choice != 'y' or choice != 'Y' evaluates to False? Additionally, De Morgan's laws may be useful to you. Commented Jul 22, 2015 at 14:12

1 Answer 1

10

You have your logic inverted. Use and instead:

while choice != 'y' and choice != 'Y' and choice != 'N' and choice != 'n':

By using or, typing in Y means choice != 'y' is true, so the other or options no longer matter. or means one of the options must be true, and for any given value of choice, there is always at least one of your != tests that is going to be true.

You could save yourself some typing work by using choice.lower() and test only against y and n, and then use membership testing:

while choice.lower() not in {'n', 'y'}:
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.