2

The following code snippet is meant to allow the user to input the answer to a question. They are allowed to enter four answers: either y or Y for “yes”, or n or N for “no”. The program is supposed to print out the received answer if the entry is valid, and print out an error message otherwise.

answer = input("What is your answer? ")
if answer == "y" or "Y":
    print("You answered yes")
elif answer == "n" or "N":
    print("You answered no")
else:
    print("You didn’t enter an acceptable answer")

It just keeps on saying that I answered yes regardless if I put n or N or some random thing. Can someone explain it to me?

Stephen Rauch
  • 44,696
  • 30
  • 102
  • 125
Sam
  • 75
  • 1
  • 5
  • Possible duplicate of [Why is my python if statement not working?](https://stackoverflow.com/questions/21790669/why-is-my-python-if-statement-not-working) – Georgy Mar 04 '18 at 18:44

3 Answers3

7

The precedence of the or is not what you are expecting. Instead try:

answer = input("What is your answer? ")
if answer in ("y", "Y"):
    print("You answered yes")
elif answer in ("n", "N"):
    print("You answered no")
else:
    print("You didn’t enter an acceptable answer")

Or maybe like:

answer = input("What is your answer? ")
if answer.lower() == "y":
    print("You answered yes")
elif answer.lower() == "n":
    print("You answered no")
else:
    print("You didn’t enter an acceptable answer")
Stephen Rauch
  • 44,696
  • 30
  • 102
  • 125
4

Your first condition will always return true because "Y" is always truthy.

Try: if answer == "y" or answer == "Y":

And the same modification for the other conditional.

Anthony L
  • 1,995
  • 11
  • 24
0

If you want to check a variable shortly as you want, use something like this:

if answer in ["y","Y"]:

It will return True if answer is y or Y

OSA413
  • 371
  • 2
  • 5
  • 15