布尔运算 [英] Boolean operations
问题描述
我对 Python 如何评估布尔语句感到困惑.
I'm confused on how Python evaluates boolean statements.
例如
False and 2 or 3
返回 3
如何评价?我认为 Python 首先查看 'False and 2',然后返回 False 甚至不查看 'or 3'.Python在这里看到的顺序是什么?
How is this evaluated? I thought Python first looks at 'False and 2', and returns False without even looking at 'or 3'. What is the order of what Python sees here?
另一个是:
1 or False and 2 or 2 and 0 or 0
返回 1
从我从第一个示例中收集到的信息,我认为 Python 会从左到右求值,因此1 或 False"将返回 1,然后1 和 2"将返回 2,然后2 或 2"将返回第一个 2,然后2 和 0"将返回 0,然后0 或 0"将返回第二个 0.
From what I gathered from the first example, I thought Python would evaluate from left to right, so '1 or False' would return 1, then '1 and 2' would return 2, then '2 or 2' would return the first 2, then '2 and 0' would return 0, then '0 or 0' would return the second 0.
正如你所知道的,我在这里很困惑,请帮忙!
As you can tell I'm pretty perplexed here, please help!
谢谢!
推荐答案
and
比 or
具有更高的优先级.
and
has higher precedence than or
.
False and 2 or 3
被评估为
((False and 2) or 3)
由于第一部分 (False and 2)
是 False
,Python 必须评估第二部分以查看整个条件是否仍然可以变为 True
与否.它可以,因为 3
的计算结果为 True
,所以返回这个操作数.
Since the first part (False and 2)
is False
, Python has to evaluated the second part to see whether the whole condition can still become True
or not. It can, since 3
evaluates to True
so this operand is returned.
类似于 1 or False and 2 or 2 and 0 or 0
被评估为
(1 or ((False and 2) or ((2 and 0) or 0)))
由于 1
的计算结果为 True
,因此无论其他操作数具有哪个值,整个条件都将为 True
.Python 可以在此时停止求值,并再次返回决定最终值的操作数.
Since 1
evaluates to True
, the whole condition will be True
, no matter which value the other operands have. Python can stop evaluating at this point and again, returns the operand that determines the final value.
在确定最终结果时尽早停止称为短路评估 并且可以描述如下:
Stopping as early as the final result is determined is called short-circuit evaluation and can be described as follows:
无论何时确定表达式的最终结果,计算都会停止,并且在 Python 中返回确定最终值的操作数的值.也就是说,假设一个从左到右的评估:
Whenever the final result of the expression is determined, the evaluation is stopped and in Python the value of the operand that determines the final value is returned. That is, assuming a left-to-right evaluation:
- 对于
and
运算符,计算结果为False
(或最后一个)的最左侧操作数 - 对于
or
运算符,计算结果为True
(或最后一个)的最左侧操作数
- for the
and
operator, the left-most operand that evaluates toFalse
(or the last one) - for the
or
operator, the left-most operand that evaluates toTrue
(or the last one)
这篇关于布尔运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!