2

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?

1
  • Yes. It's shortcircuited. Commented Jan 1, 2016 at 18:35

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

2

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

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.