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!
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.