2

Can anyone explain this behaviour in Python (2.7 and 3)

>>> a = "Monday" and "tuesday"
>>> a
'tuesday'             # I expected this to be True
>>> a == True
False                 # I expected this to be True
>>> a is True
False                 # I expected this to be True
>>> a = "Monday" or "tuesday"
>>> a
'Monday'              # I expected this to be True
>>> a == True
False                 # I expected this to be True
>>> a is True
False                 # I expected this to be True

I would expect that because I am using logic operators and and or, the statements would be evaluated as a = bool("Monday") and bool("tuesday").

So what is happening here?

excalibur1491
  • 1,201
  • 2
  • 14
  • 29
  • https://www.geeksforgeeks.org/g-fact-43-logical-operators-on-string-in-python/ this may help you – Wright Mar 06 '18 at 04:56
  • 3
    Possible duplicate of [Using "and" and "or" operator with Python strings](https://stackoverflow.com/questions/19213535/using-and-and-or-operator-with-python-strings) – user3483203 Mar 06 '18 at 04:56
  • 1
    The `and` and `or` operators do not return `boolean` objects, they return either of their arguments (which could be anything) – juanpa.arrivillaga Mar 06 '18 at 04:59
  • Possible duplicate of [Does Python support short-circuiting?](https://stackoverflow.com/questions/2580136/does-python-support-short-circuiting) – Alan Hoover Mar 06 '18 at 05:00
  • @juanpa.arrivillaga, it appears you are right. It just seems so unintuitive... To me, `and` and `or` are functions that take 2 `bools` and return a `bool`. But I guess I had the wrong intuition. Thanks! – excalibur1491 Mar 06 '18 at 05:06

1 Answers1

4

As explained here using and / or on strings will yield the following result:

  • a or b returns a if a is True, else returns b.
  • a and b returns b if a is True, else returns a.

This behavior is called Short-circuit_evaluation and it applies for both and, or as can be seen here.

This explains why a == 'tuesday' in the 1st case and 'Monday' in the 2nd.

As for checking a == True, a is True, using logical operators on strings yields a specific result (as explained in above), and it is not the same as bool("some_string").

CIsForCookies
  • 12,097
  • 11
  • 59
  • 124
  • I expected the result of `"monday" and "tuesday"` to be a `bool`, In my mind (and I guess whoever wrote most of the other languages) `and` is an (overloaded) operator that returns a `bool`. Thanks for the explanation – excalibur1491 Mar 06 '18 at 05:02