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
  • 47,830
  • 31
  • 106
  • 135
Sam
  • 75
  • 1
  • 5

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
  • 47,830
  • 31
  • 106
  • 135
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
  • 2,159
  • 13
  • 25
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
  • 387
  • 2
  • 4
  • 16