How do boolean operations work with parentheses in python 2.7?

南楼画角 提交于 2019-12-13 04:26:10

问题


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.


回答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
>>> 2 or 0
2
>>> 0 and 2
0

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



回答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']


来源:https://stackoverflow.com/questions/23350423/how-do-boolean-operations-work-with-parentheses-in-python-2-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!