我正在运行一个Python脚本,测试两个条件的结合,其中一个很容易验证,另一个很难验证。假设我用Python将它写成easy_boole and hard_boole。解释器是否总是先检查easy_boole,然后返回False(如果easy_boole == False)?解释器是否进行了总体优化,以尽快解析这类语句?你知道吗
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
>>> 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
是的,
and
和or
都是所谓的短路算子。值为假时,and
表达式的求值结束,值为真时,or
表达式的求值结束。你知道吗您可以找到相关文档here。你知道吗
下面是一段代码,您可以自己观察这种行为:
所以记住,一定要使用
easy_boole and hard_boole
。你知道吗只需打开一个REPL并尝试:
这意味着Python确实是懒洋洋地计算布尔语句的。你知道吗
另外,这是一个duplicate
从Python Documentation:
因此,只要
x
是False
,表达式的值就会是False
相关问题 更多 >
编程相关推荐