0

I can't figure out why this while loop is not working properly.

bday = input("Has your birthday already passed? (y|n) : ")

print(bday)

while True:
    if (bday != 'y' or bday != 'Y' or bday != 'n' or bday != 'N'):
        print("Invalid input, please enter Y or N.")
        print(bday)
        bday = input("Has your birthday already passed? (y|n) : ")
    else:
        break

According to my print statements, my values for "bday" are correctly seen as "y", "Y", "n", or "N". However, for some reason the condition acts as if it is the wrong value.

Originally coded as:

while (bday != 'y' or bday != 'Y' or bday != 'n' or bday != 'N'):
   print("Invalid input, please enter Y or N.")
   print(bday)
   bday = input("Has your birthday already passed? (y|n) : ")

Thanks for any help.

2
  • The conditions in your if statement should be anded together. Currently, regardless of input, that condition will always be true. Commented Nov 8, 2018 at 16:11
  • Every string is not equal to at least one of 'y', 'Y', 'n', 'N'. It's impossible for a string to be equal to all of those. Commented Nov 8, 2018 at 17:04

2 Answers 2

3

Your if statement(s) need to be and not or. Although I suggest using not in and a list and checking that to bday.lower():

bday = input("Has your birthday already passed? (y|n) : ")

print(bday)

while True:
    if bday.lower() not in ['y', 'n']:
        print("Invalid input, please enter Y or N.")
        print(bday)
        bday = input("Has your birthday already passed? (y|n) : ")
    else:
        break
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer! And I didn't know about not in, so thanks for that too it looks really useful.
1

There is an error in the logic. If you want your program to ask the user again if the input is not ('y' or 'Y' or 'n' or 'N') , you have to use 'and' instead of 'or'

Try:

while True:
    bday = input("Has your birthday already passed? (y|n) : ")
    if ((bday != 'y') and (bday != 'Y') and (bday != 'n') and (bday != 'Y')):
        print("Invalid input, please enter Y or N.")
    else:
        break

2 Comments

Do you really need so many braces? It might clean up your code a bit
Of course not. I just wrote it this way trying to explain the logic as clear as possible. In fact, the best way is using Jaba's response. :)

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.