详解Python 中的短路评估
作者:迹忆客
本文是关于使用逻辑运算符在 Python 中显示短路行为。
Python 中的逻辑运算符
or (或)运算符
OR:两个操作数均使用 Python or 运算符求值。 如果任一操作数为 True,则 or 运算符返回 True。
但是,仅当所有给定表达式或操作数都返回 False 时,or 运算符才会返回 False。
OR运算符逻辑表:
第一值 | 第二值 | 输出 |
---|---|---|
True | True | True |
True | False | True |
False | True | True |
False | False | False |
上述 OR 运算符在 Python 控制台中的表示:
>>> True or True True >>> True or False True >>> False or True True >>> False or False False
Python 还允许我们使用 OR 运算符比较多个表达式。
>>> (5 < 10) or (8 < 5) True >>> (5 < 10) or (8 < 5) or (2 == 2) or (9 != 8) True
AND 运算符
AND:当使用 Python and 运算符时,两个操作数都会被求值,如果任何给定的表达式或运算符不为真,则返回 False。 and 运算符仅在给定表达式或操作数都为 True 时才返回 True。
AND运算符逻辑表:
第一值 | 第二值 | 输出 |
---|---|---|
True | True | True |
True | False | False |
False | True | False |
False | False | False |
上述 AND 运算符在 Python 控制台中的表示:
>>> True and True True >>> True and False False >>> False and True False >>> False and False False
使用 AND 运算符比较多个表达式。
>>> (5 < 10) and (8 < 5) False >>> (5 < 10) and (8 < 5) and (2 == 2) and (9 != 8) False >>> (10 == 10) and (8 != 5) and (2 == 2) and (9 != 8) True
什么是短路
短路是指当表达式的真值已经确定时终止布尔运算。 Python 解释器以从左到右的方式计算表达式。
Python 的大量布尔运算符和函数允许短路。
def exp(n): print("Hello") return n
为了了解短路是如何发生的,我们将使用上述函数作为操作数或表达式之一,当 Python 解释器执行它时,它将打印单词“Hello”。
在 Python 中使用 AND 运算符进行短路
使用 and 运算符:
>>> True and exp(1) Hello 1
Python 解释器在上面的代码中从左到右评估代码。 根据 AND 运算符的逻辑表,表达式必须为 True 才能得到 True 布尔值。
Python 解释器评估我们的函数只是因为第一个值设置为 True。
如果我们将初始值设置为 False 会怎样? 观察下面的代码:
>>> False and exp(1) False
由于初始值设置为 False,Python 解释器会忽略后面的表达式,从而节省执行时间。
交换表达式:
>>> exp(1) and True Hello True >>> exp(1) and False Hello False
在这些代码中,我们的初始表达式是我们之前创建的函数。 Python 解释器首先评估给定的函数,导致输出“Hello”。
在 Python 中使用 OR 运算符进行短路
使用或运算符:
>>> True or exp(1) True
从左到右评估代码。 将初始值设置为 True 可以让 Python 解释器忽略后面表达式的执行,也就是给定的函数。
因此,根据 OR 运算符的给定逻辑表,输出为 True。
>>> False or exp(1) Hello 1
Python 解释器执行上面代码中的函数,因为前一个值设置为 False。
交换表达式:
>>> exp(1) or True Hello 1 >>> exp(1) or False Hello 1
当我们交换表达式时,我们创建的函数每次都会执行,因为它是 Python 解释器评估的第一个操作数。
考虑以上任一代码示例,or 运算符将返回 True 布尔值。
但是,如果我们使用 or 运算符得到一个 False 布尔值,我们可以稍微调整创建的函数。
def exp(): print("Hello") return False >>> exp() Hello False
经过以上改动后,每当我们调用 exp()
函数时,它只会在向控制台打印 Hello 后返回 False 布尔值。
>>> exp() or True Hello True >>> exp() or False Hello False
由于该函数在每次调用时只返回一个 False 布尔值,Python 解释器必须评估后一个表达式或操作数。
到此这篇关于Python 中的短路评估的文章就介绍到这了,更多相关Python短路评估内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!