Python:Short Circuiting -- “OR”
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 ""
分析
short-circuit operator
:之所以说or
是“短路操作符”,是因为当第一个操作数为True
的时候,or
便会得出整体表达式为True
的结论,这样就不会执行下一个操作数。(and
同理)- 整体的返回值:就如上面所说,:
and
和or
总是会返回最后一个计算的值,无论他们是否短路。短路时最后一个返回值就是第一个操作数,不短路时就会返回计算的第二个操作数的值。
这样当表达式print(3) or ""
执行到第一个操作数print(3)
时,因为函数print()
输出3
后,返回的是None
,None
在逻辑上被视为 False
,因此会继续判断第二个操作数。这时候output只有一个3
。计算第二个操作数""
即为''
空字符串,这时会输出''
。
这样输出结果为:
>>> print(3) or "" 3 ''
本文作者:上山砍大树
本文链接:https://www.cnblogs.com/shangshankandashu/p/18026140
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步