fbpx

What is Short Circuit Evaluation in Python?

Short circuit evaluation in any programming language is the act of not executing unnecessary parts of a Boolean expression.

Say, you want to calculate the result of the expression “A and B” but you already know that “A=False”. Because of your knowledge of the first part of the expression, you already know that the result to the overall expression (it evaluates to “False”). So the programming language skips computation of the remaining expressions and just returns the result.

Another example is the expression “A or B” and you already know that “A=True”. Now, you can simply skip all remaining computations and return “True” right away which is the result of the overall computation.

Here’s an interesting example:

a = 1 > 0

if a or (1 / 0 == 0):
    print('ok')
else:
    print('nok')

# Result is 'ok'

The right-hand side of the expression (1 / 0 == 0) is not executed. So Python does not throw the error ‘cannot divide by zero’.

Where to go from here?

Python is full of those small optimizations. Every master coder knows them? Want to learn them, step-by-step, day-by-day? Join my free Python email course for continuous improvement! It’s fun!

[Free Cheat Sheets] “Coffee Break Python” Email Course with Python Cheat Sheets!

Leave a Comment

Your email address will not be published. Required fields are marked *