Python 中的布尔表达式
Boolean expressions in Python
我有一个 Python 脚本,我是 运行,它测试两个条件的结合,其中一个很容易验证,另一个很难。假设我在 Python 中将其写为 easy_boole and hard_boole
。解释器是否总是先检查 easy_boole
然后检查 return False
如果 easy_boole == False
?解释器是否总体上经过优化以尽快解决这些类型的语句?
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.
所以只要x
是False
,表达式就会被计算为False
是的,and
和 or
都是所谓的 short-circuit 运算符。 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
。
是的,python 延迟计算 if 语句。例如,在以下代码中:
if f() and g():
print("GOOD")
else:
print("BAD")
Python 解释器首先会检查 f() 语句,如果 f() 为 False,它会立即跳转到 else 语句。
只需打开一个 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 确实延迟计算布尔语句。
P.S。这是一个 duplicate
我有一个 Python 脚本,我是 运行,它测试两个条件的结合,其中一个很容易验证,另一个很难。假设我在 Python 中将其写为 easy_boole and hard_boole
。解释器是否总是先检查 easy_boole
然后检查 return False
如果 easy_boole == False
?解释器是否总体上经过优化以尽快解决这些类型的语句?
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.
所以只要x
是False
,表达式就会被计算为False
是的,and
和 or
都是所谓的 short-circuit 运算符。 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
。
是的,python 延迟计算 if 语句。例如,在以下代码中:
if f() and g():
print("GOOD")
else:
print("BAD")
Python 解释器首先会检查 f() 语句,如果 f() 为 False,它会立即跳转到 else 语句。
只需打开一个 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 确实延迟计算布尔语句。
P.S。这是一个 duplicate