excalibur1491
excalibur1491

Reputation: 1221

Booleans interpretted from strings, unexpected behavior

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?

Upvotes: 2

Views: 75

Answers (1)

CIsForCookies
CIsForCookies

Reputation: 12817

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").

Upvotes: 4

Related Questions