I have a Python script I'm running that tests for the conjunction of two conditions, one of which is easy to verify and the other hard. Say I write it as easy_boole and hard_boole in Python. Will the interpreter always check easy_boole first and then return False if easy_boole == False? Is the interpreter optimized in general to resolve these kinds of statements as quickly as possible?
-
Yes. It's shortcircuited.Josep Valls– Josep Valls2016-01-01 18:35:49 +00:00Commented Jan 1, 2016 at 18:35
4 Answers
Yes, both and and or are so called short-circuit operators. The evaluation of an and expression ends as soon as a value is falsy, the evaluation of an or expression ends as soon as a value is truthy.
You can find the relevant documentation here.
Here is a piece of code with which you can observe this behavior yourself:
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
So with that in mind, always use easy_boole and hard_boole.
Comments
Just open up a REPL and try:
>>> 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
That means that Python indeed evaluates boolean statements lazily.
P.S. It's a duplicate
Comments
From 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.
So as long as x is False, the expression will be evaluated to False