Python Forum

Full Version: While loop issue
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm trying to understand why this code works..
count = 0
while (count < 9):
   print ('The count is:', count)
   count = count + 1

print ("All done")
but this one doesn't...
answer = ""
while (answer != 'y' or 'n'):
    answer = input('Please enter y/n): ')

print("got here")
In the second case it loops continuously no matter what the user enters. I'm obviously missing something.
Thanks.

Just for completeness I used this which works

answer = ""
while answer not in ("Y", "y", "N", "n"):
    answer = input('Please enter y/n): ')
print("got here")
thanks for sharing back. Yours is perfectly fine, but If I may suggest, I would do
answer = ""
while answer.lower() not in ("y","n"):
    answer = input('Please enter y/n): ')
print("got here"))
but it's matter of preference - i.e. shorter tuple to look into
Or even while answer.lower() not in "yn":.  Since strings are already iterables, and you're matching a single character, it's the same as a tuple/list of single character strings.

...actually, don't do that.  Because then someone could just type "yn", and it'd be valid.  Unless you only took the first character of answer... while answer[0].lower() not in "yn":