Ask coding questions

← Back to all posts
I need help making this work
JavasLava (0)

https://repl.it/@JavasLava/Javas-Bitch-Lasagna

For some reason, whenever I put in N or n as my input, the output comes out as if I put in Y or y.

My code is this:

name = input("What is your name? ")
print("Hello there " + name)
doing = input("What are you doing? ")
print("Wow, Im doing " + doing + " Too")
join = input("Would you like to join me? Y or N")

if join == "Y" or "y":
print("Alright, join me")
elif join == "N" or "n":
print("Okay bye")
else:
print("answer something valid")

It's simple I know.

Commentshotnewtop
MatthewDoan1 (35)

Take a look at truthy and falsey values. The part of your code that's wrong is this part here:

if join == "Y" or "y":
  print("Alright, join me")
elif join == "N" or "n":
  print("Okay bye")
else:
  print("answer something valid")

Actually, the faulty line is right here:

if join == "Y" or "y":

In English, it seems natural to us that something can equal to x or y. For example:
"What's for dinner tonight, Mom?"
"Tonight we're having pizza or spaghetti, Jimmy John."

So our innate knowledge of this carries over to programming. HOWEVER, if you type something like

if "abc":
    print("123")

Guess what: This code is (syntactically, at least) correct! The output is 123. This is because "abc" is a truthy value. I'm going to do my best to explain it here, but a quick Google search will probably give you a better definition.

Truthy values are values that, when put in an if-statement or while-loop, evaluate to True. What makes a value truthy? Good question - here's the list.

  • The boolean True
  • Any number that isn't 0 (floats or integers)
  • Non-empty strings
  • Non-empty lists
  • Non-empty dictionaries

All other values are falsey.

Now here's where your error comes from. Lets separate this ifright here:

if join == "Y" or "y":
  print("Alright, join me")

into two branches. So the line

print("Alright, join me")

will only execute IF either

  • join == "Y" or
  • "y"

Now, remember earlier, "y" is a truthy value. So this is why the first if-statement always finds the conditional true.

I would recommend changing your code to:

join = input("Would you like to join me? Y or N").lower()

if join == "y":
  print("Alright, join me")
elif join == "n":
  print("Okay bye")

Or, even better:

join = input("Would you like to join me? Y or N")

if join in ["Y", "y"]:
  print("Alright, join me")
elif join in ["N", "n"]:
  print("Okay bye)

This is a better solution because the second example allows you to add more valid responses (e.g. adding "yes" and "no" to the answer lists).

I hoped this helped you with your code and understanding truthy and falsey values in Python.

Yours truly,
Matthew