Flat_Eric Contemplating Data Type Conversions

Short Circuiting

Short Circuiting

In the previous lessons we used the and keyword to combine two conditions. When using and, both conditions must be True for the block to run. But what actually happens behind the scenes when Python evaluates those conditions?

The answer is short circuiting. Instead of evaluating every condition in an expression, Python takes a shortcut. It reads the conditions from left to right and stops as soon as the outcome is determined.

With and, if the first condition is False, Python already knows the whole expression cannot be True, so it stops immediately and does not bother checking the rest. There is no point checking the second condition if the first one already failed.

With or, the opposite is true. If the first condition is True, Python already knows the whole expression is True and stops without checking the rest. It only continues if the first condition is False.

This is not just a performance trick. Short circuiting has practical uses in your code that we will explore in the next section.

Short Circuiting in Action

In this example we are checking whether a car is roadworthy. Both conditions must pass before the car is allowed on the road. Notice that if the first condition fails, Python never checks the second one.

Try setting has_valid_licence to False and run it again. Python will stop at the first condition and never evaluate has_valid_insurance.

Time to experiment!

Coding Exercises (VS Code) Instructions:

Exercise 1: and Short Circuit

Exercise 2: or Short Circuit

Exercise 3: Real World Short Circuit

Don't Forget to commit and Push!

This course was built by DevSTEM - we turn teaching materials into interactive web courses like this one.

Build your own course