-1

I just stumbled on what seems a bug to me :

var = "2"
if var is "" or "1":
    print(var)

This piece of code returns "2" as I expect it to print nothing.

Can someone explains this result to me ?

Tested on 2.7 and 3.4

Arnus
  • 3
  • 1
  • 1
    It may help to understand that this is parsed as `if ((var is "") or ("1"))` so you need to understand how `is` works and what the meaning of `"1"` is when considered as a boolean – Ben Mar 19 '19 at 07:57
  • `is` operator: https://stackoverflow.com/questions/13650293/understanding-pythons-is-operator – Ben Mar 19 '19 at 07:58
  • See truth value testing here: https://docs.python.org/2/library/stdtypes.html?highlight=type%20conversions – Ben Mar 19 '19 at 08:00

1 Answers1

0
  1. Your expression is parsed as (var is "") or "1", which is always True, because "1"is True-ish.

  2. If you add parentheses to get var is ("" or "1"), that is equvalent to var is True, because "" or "1" is True, because "1" is True-ish.

  3. Comparing strings with is is fraught with peril, because the is operator checks identity, not equality.

You probably want var in ("", "1")

Ture Pålsson
  • 6,088
  • 2
  • 12
  • 15
  • Yes, obvious mistake from me, I shall pay more attention next time... Thank you for the answer anyway ! – Arnus Mar 20 '19 at 08:43