Reputation: 5
Here's the code I have question with:
isPet_list_elem = input("Pet?: ").lower()
# check if the input is either y or n
while isPet_list_elem != "y" or isPet_list_elem != "n":
print("Please enter either 'y' or 'n'.")
isPet_list_elem = input("Pet?: ").lower()
I keep thinking that the loop would end when I enter either "y" or "n", but the loop continues to ask me for another input even after entering either y or n.
I've tried using other while loop to do the same, but the result was the same. What should I do to avoid this error?
Upvotes: 0
Views: 88
Reputation: 1
Include the following inside while loop:
if isPet_list_elem == "y" or isPet_list_elem == "n":
break
Upvotes: 0
Reputation: 52
If you enter "y", then isPet_list_elem != "n"
is true; if you enter "n", then isPet_list_elem != "y"
is true. And you use or
in your code, so, if one expressin is true, the whole statement will be true.
you can use the following code instead:
while isPet_list_elem != "y" and isPet_list_elem != "n"
Upvotes: 0
Reputation: 4606
You can just do this and this will break the loop for y
or n
while isPet_list_elem not in ('y','n'):
Upvotes: 1
Reputation: 1371
You are using the wrong logic. When you enter y
or n
with your code, the condition at the beginning of the loop comes out as True
so it continues to execute. Change it to an and
statement and once y
or n
is entered, the condition will be False
.
isPet_list_elem = input("Pet?: ").lower()
# check if the input is either y or n
while isPet_list_elem != "y" and isPet_list_elem != "n":
print("Please enter either 'y' or 'n'.")
isPet_list_elem = input("Pet?: ").lower()
Upvotes: 0
Reputation: 763
It's Demorgan's law.
You can say:
while isPet_list_elem != "y" and isPet_list_elem != "n"
or
while not (isPet_list_elem == "y" or isPet_list_elem == "n")
Upvotes: 2