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?

- 995
- 2
- 10
- 23
-
Yes. It's shortcircuited. – Josep Valls Jan 01 '16 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
.

- 76,762
- 20
- 123
- 145
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

- 1,922
- 16
- 23
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

- 10,739
- 2
- 18
- 34
Yes, python evaluates if statements lazily. For example, in following code:
if f() and g():
print("GOOD")
else:
print("BAD")
Python interpreter will first check f() statement and if f() is False, it will immediately jump on else statement.

- 297
- 1
- 7