Python Forum
While loop issue - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: While loop issue (/thread-5230.html)



While loop issue - CWatters - Sep-23-2017

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.


RE: While loop issue - buran - Sep-23-2017

https://python-forum.io/Thread-Multiple-expressions-with-or-keyword


RE: While loop issue - CWatters - Sep-23-2017

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



RE: While loop issue - buran - Sep-24-2017

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


RE: While loop issue - nilamo - Sep-25-2017

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