Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
While loop issue
#1
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.
Reply
#2
https://python-forum.io/Thread-Multiple-...or-keyword
Reply
#3
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")
Reply
#4
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
Reply
#5
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":
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  For List Loop Issue Galdain 2 2,061 Dec-31-2019, 04:53 AM
Last Post: Galdain
  issue with updating list every iteration of a loop ftrillaudp 2 3,075 Oct-29-2018, 03:23 AM
Last Post: ftrillaudp
  while loop issue, help please? itmustbebunnies 6 3,037 Oct-25-2018, 07:22 AM
Last Post: itmustbebunnies
  for-loop issue digysol 2 2,095 Oct-24-2018, 06:12 PM
Last Post: nilamo
  Issue with my 'roll the dice simulation'-exercise (cannot break out of the loop) Placebo 2 3,522 Sep-30-2018, 01:19 PM
Last Post: Placebo
  while loop issue - stuck in the loop! EricMichel 6 8,622 Aug-06-2018, 03:59 PM
Last Post: EricMichel
  Loop issue onenessboy 11 6,755 Mar-03-2018, 08:40 AM
Last Post: onenessboy
  Code issue with time remaining loop. Python3 deboerdn2000 11 8,852 May-04-2017, 04:53 PM
Last Post: deboerdn2000

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020