-1
code = (input("Write a number: "))
print (code)
if code == "1" or "2":
    print ("bad")
elif code =="3":
    print ("good")
else:
    print ("hmmm"  )

Output:

Write a number: 3
3
bad

I'm confused, shouldn't the output be "good" instead of "bad"?

takendarkk
  • 3,347
  • 8
  • 25
  • 37

1 Answers1

2

The syntax of your logic is wrong: if code=="1" or code=="2":

What you originally had (if code == "1" or "2") is understood by the interpreter as asking the following two questions:

  1. Does the value in code == "1"?
  2. Is "2" true?

The second question will always evaluate to True. So the if clause will always run.

  • just to add on to the answer above, but in your case you can use `if code in ('1', '2')` which should do what you're expecting. all this does is check if `code` is within the collection, in this case a tuple. – rv.kvetch Sep 30 '21 at 15:32