Skip to content Skip to sidebar Skip to footer

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'

Solution 1:

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
>>>2or0
2
>>>0and2
0

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

Solution 2:

  • 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']

Post a Comment for "How Do Boolean Operations Work With Parentheses In Python 2.7?"