Eli Dinkelspiel
Eli Dinkelspiel

Reputation: 779

How do boolean operations work with parentheses in python 2.7?

Found this little oddity while playing around.

>>> 'Hello' == ('Hello' or 'World')
True
>>> 'Hello' == ('World' or 'Hello')
False
>>> 'Hello' == ('Hello' and 'World')
False
>>> 'Hello' == ('World' and 'Hello')
True

Is there some trick to this logic that I'm not getting? Why is the order of the strings the determining factor of these queries? Should I not be using parentheses at all? Why does changing to "and" flip the outputs?

Thanks a buncharooni.

Upvotes: 1

Views: 650

Answers (2)

Henry Keiter
Henry Keiter

Reputation: 17188

In Python, all objects may be considered "truthy" or "falsy". Python uses this fact to create a sneaky shortcut when evaluating boolean logic. If it encounters a value that would allow the logic to "short-circuit", such as a True at the beginning of an or, or a False at the start of an and, it simply returns the definitive value. This works because that value itself evaluates appropriately to be truthy or falsy, and therefore whatever boolean context it's being used in continues to function as expected. In fact, such operations always just return the first value they encounter that allows them to fully evaluate the expression (even if it's the last value).

# "short-circuit" behavior
>>> 2 or 0
2
>>> 0 and 2
0

# "normal" (fully-evaluated) behavior
>>> 'cat' and 'dog'
'dog'
>>> 0 or 2
2

Upvotes: 3

recursive
recursive

Reputation: 86134

  • x or y returns the first operand if its truthy, otherwise returns the second operand.
  • x and y returns the first operand if its falsey, otherwise returns the second operand.

For what it looks like you're trying to accomplish you may prefer this:

'Hello' in ['Hello', 'World']

Upvotes: 2

Related Questions