0

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?

3
  • 3
    Your boolean operator in the while clause should be and and not or. Commented Sep 26, 2018 at 23:56
  • Aha! Shouldn't I need or to return True for either situations? Commented Sep 27, 2018 at 0:01
  • 1
    If isPet_list_elem = "n" then isPet_list_elem != "y" is true, so the total expression is true. If isPet_list_elem = "y" then isPet_list_elem != "n" is true, so your total expression is true. So in any case your expression is true. Commented Sep 27, 2018 at 0:03

5 Answers 5

2

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")
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, ok. De Morgan's Law but the question had nothing to do with De Morgan's law. He was using the wrong logic in the condition for his while loop.
The question had everything to do with De Morgan's Law. That's why the original code didn't work.
1

You can just do this and this will break the loop for y or n

while isPet_list_elem not in ('y','n'):

1 Comment

correct I just thought about that and came back here
0

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

Comments

0

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"

Comments

0

Include the following inside while loop:

    if isPet_list_elem == "y" or isPet_list_elem == "n":
            break

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.