Python 布尔表达式 and or
在 python 中,如果你编写类似
foo==bar and spam or eggs
python 的东西,如果布尔语句为真,则返回垃圾邮件,否则返回鸡蛋。有人可以解释这种行为吗?为什么表达式不像一个长布尔值那样被计算?
编辑:具体来说,我试图找出“垃圾邮件”或“鸡蛋”作为表达式结果返回的机制。
In python if you write something like
foo==bar and spam or eggs
python appears to return spam if the boolean statement is true and eggs otherwise. Could someone explain this behaviour? Why is the expression not being evaluated like one long boolean?
Edit: Specifically, I'm trying to figure out the mechanism why 'spam' or 'eggs' is being returned as the result of the expression.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
运算符
and
和or
是短路运算符,这意味着如果可以通过仅计算第一个操作数来推导出表达式的结果,则不会计算第二个操作数。例如,如果您有表达式a 或 b
并且a
的计算结果为 true,那么b
的结果是什么并不重要表达式为 true,因此不计算b
。它们实际上的工作原理如下:a 和 b
:如果 a 为 false,则不计算 b 并返回 a,否则返回 b。a 或 b
:如果 a 为真,则不计算 b 并返回 a,否则返回 b。Falsey 和 true 是指在布尔上下文中计算结果为 false 或 true 的值。
然而,这个 and/or 习语在当时没有更好的选择的时候很有用,但现在有更好的方法:
and/or 习语的问题(除了让初学者感到困惑之外)是它给出了错误的结果如果条件为真,但垃圾邮件计算结果为假值(例如空字符串),则结果。因此你应该避免它。
The operators
and
andor
are short-circuiting which means that if the result of the expression can be deduced from evaluating only the first operand, the second is not evaluated. For example if you have the expressiona or b
anda
evaluates to true then it doesn't matter whatb
is, the result of the expression is true sob
is not evaluated. They actually work as follows:a and b
: If a is falsey, b is not evaluated and a is returned, otherwise b is returned.a or b
: If a is truthy, b is not evaluated and a is returned, otherwise b is returned.Falsey and truthy refer to values that evaluate to false or true in a boolean context.
However this and/or idiom was useful back in the days when there was no better alternative, but now there is a better way:
The problem with the and/or idiom (apart from it being confusing to beginners) is that it gives the wrong result if the condition is true but spam evaluates to a falsey value (e.g. the empty string). For this reason you should avoid it.
这就是 Python 布尔运算符的工作原理。
来自 文档 (最后一段解释了为什么它是一个好主意,操作员按照他们的方式工作):
This is how the Python boolean operators work.
From the documentation (the last paragraph explains why it is a good idea that the operators work the way they do):
原因是 Python 使用所涉及变量的实际值来计算布尔表达式,而不是将它们限制为
True
和False
值。以下值被视为 false:None
False
''
,()
、[]
、{}
)__nonzero__()
或__len__()
的用户定义类型> 返回 0 或False
的方法请参阅 有关详细信息,请参阅 Python 文档的真值测试部分。尤其:
The reason is that Python evaluates boolean expression using the actual values of the variables involved, instead of restricting them to
True
andFalse
values. The following values are considered to be false:None
False
''
,()
,[]
,{}
)__nonzero__()
or__len__()
method that returns 0 orFalse
See the Truth Value Testing section of the Python documentation for more information. In particular:
尝试使用括号使表达式不含糊。就这样,你会得到:
Try using parentheses to make the expression non-ambiguous. The way it is, you're getting: