Short Circuiting
Operator | Checks if: | Evaluates from left to right up to: | Example |
---|---|---|---|
AND | All values are true | The first false value | False and 1 / 0 evaluates to False |
OR | At least one value is true | The first true value | True or 1 / 0 evaluates to True |
Short-circuiting happens when the operator reaches an operand that allows them to make a conclusion about the expression. For example, and
will short-circuit as soon as it reaches the first false value because it then knows that not all the values are true.
If and
and or
do not short-circuit, they just return the last value; another way to remember this is that and
and or
always return the last thing they evaluate, whether they short circuit or not. Keep in mind that and
and or
don't always return booleans when using values other than True
and False
.
举例
---------------------------------------------------------------------
The Truth Will Prevail > Suite 2 > Case 2
(cases remaining: 2)
What would Python display? If you get stuck, try it out in the Python
interpreter!
>>> print(3) or ""
分析
因为操作符or
的短路特性,会让这个操作符寻找第一个值为True
的值。如果左边的值不为True
,那么就会执行右边的值。
这里print()
返回为None
,同等于逻辑False
。这样or
便会执行下一个表达式""
。这样便会输出''
,即空字符串。