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 ""

分析

  1. short-circuit operator:之所以说or是“短路操作符”,是因为当第一个操作数为True的时候,or便会得出整体表达式为True的结论,这样就不会执行下一个操作数。(and同理)
  2. 整体的返回值:就如上面所说,:andor总是会返回最后一个计算的值,无论他们是否短路。短路时最后一个返回值就是第一个操作数,不短路时就会返回计算的第二个操作数的值。

这样当表达式print(3) or ""执行到第一个操作数print(3)时,因为函数print()输出3后,返回的是NoneNone 在逻辑上被视为 False,因此会继续判断第二个操作数。这时候output只有一个3。计算第二个操作数""即为''空字符串,这时会输出''

这样输出结果为:

>>> print(3) or ""
3
''
posted @ 2024-02-21 20:18  上山砍大树  阅读(6)  评论(0编辑  收藏  举报