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
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'}:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.