在python 2.7中,布尔运算如何与括号一起使用? [英] How do boolean operations work with parentheses in python 2.7?

查看:234
本文介绍了在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?

感谢布加罗尼.

推荐答案

在Python中,所有对象都可以视为真实"或虚假".在评估布尔逻辑时,Python使用此事实创建了一个偷偷摸摸的快捷方式.如果遇到允许逻辑短路"的值,例如or开头的Trueand开头的False,则只需返回确定值.之所以可行,是因为该值 itself 正确评估为真实还是虚假,因此,无论使用哪种布尔上下文,它都可以按预期运行.实际上,此类操作总是只会返回它们遇到的第一个值,使他们可以完全评估表达式(即使它是最后一个值).

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

这篇关于在python 2.7中,布尔运算如何与括号一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆