dsaxton
dsaxton

Reputation: 1015

Boolean expressions in Python

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?

Upvotes: 2

Views: 248

Answers (4)

timgeb
timgeb

Reputation: 78790

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.

Upvotes: 3

Iron Fist
Iron Fist

Reputation: 10961

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

Upvotes: 2

vrs
vrs

Reputation: 1982

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

Upvotes: 3

Andreikkaa
Andreikkaa

Reputation: 297

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.

Upvotes: 0

Related Questions