0

I have this (simplified):

    foo = input("Test")
    if foo is "a" or "b":
        print("Test")

This returns Test for everything that the user inputs, while those work and only return when a or b is given.

    foo = input("Test")
    if foo is "a" or foo is "b":
        print("Test")

-

    foo = input("Test")
    if foo in ("a" or "b"):
        print("Test")

Why does the first one not work?

I can only guess that the first one actually checks if foo == "a", but not if foo == "b", and that the or "b" part always returns True - but why?

Flying Thunder
  • 890
  • 2
  • 11
  • 37
  • 3
    The first line is evaluating `"b"` as `True`. To see how python evaluates the 'truthiness' of different objects use `bool()`. – Chris Mueller Sep 24 '18 at 12:48
  • 2
    The question is not the same as the linked one. The OP *knows* the answer already, and asks why the alternatives don't work – blue_note Sep 24 '18 at 12:49
  • To answer you question, the first one does not work because `if foo is "a" or "b"` checks `(foo is "a") or ("b")`. When the character "b" is evaluated as a boolean is considered True (anything that is not 0 or None is considered True). So `(foo is "a") or (True) = True` – Amedeo Sep 24 '18 at 12:53
  • @blue_note Martijn's answer in the first linked dupe gives the reason that the 'simplified' version does not work. – SiHa Sep 24 '18 at 12:58
  • And use `==` for string comparison, `is` is for object identity. – Klaus D. Sep 24 '18 at 13:11
  • Actually, it seems that the 3rd does NOT return True - whats the shortest way to check this then? The second one seems very redundant to me. I assume the shortest way is putting `"a"` and `"b"` in a list? the `("a" or "b")` did not work, i thought that brackets would help just like in math – Flying Thunder Sep 25 '18 at 11:41

0 Answers0