Python中的布尔表达式

2024-10-02 18:18:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在运行一个Python脚本,测试两个条件的结合,其中一个很容易验证,另一个很难验证。假设我用Python将它写成easy_boole and hard_boole。解释器是否总是先检查easy_boole,然后返回False(如果easy_boole == False)?解释器是否进行了总体优化,以尽快解析这类语句?你知道吗


Tags: and脚本falseeasy语句条件解释器总体
3条回答

是的,andor都是所谓的短路算子。值为假时,and表达式的求值结束,值为真时,or表达式的求值结束。你知道吗

您可以找到相关文档here。你知道吗

下面是一段代码,您可以自己观察这种行为:

def fib(n):
    if n <= 2:
        return 1
    return fib(n-1) + fib(n-2)

print(False and fib(100)) # prints False immediately
print(True and fib(100)) # takes very, very long
print(fib(100) and False) # takes very, very long

所以记住,一定要使用easy_boole and hard_boole。你知道吗

只需打开一个REPL并尝试:

>>> False and 1 / 0
False

>> True or 1 / 0
True

>>> False or 1 / 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

这意味着Python确实是懒洋洋地计算布尔语句的。你知道吗

另外,这是一个duplicate

Python Documentation

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

因此,只要xFalse,表达式的值就会是False

相关问题 更多 >