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:
- Create a file named short_circuiting.py in your part41 folder.
- Complete the tasks and use # comments to explain your answers.
Exercise 1: and Short Circuit
-
Task: Create two variables
has_passport = Falseandhas_boarding_pass = True. -
Goal: Write an
ifstatement usingandthat prints"Passenger can board."if both areTrueand"Boarding denied."if not. Write a comment explaining which condition Python stops at and why it does not check the second one.
Exercise 2: or Short Circuit
-
Task: Create two variables
is_vip = Trueandhas_ticket = False. -
Goal: Write an
ifstatement usingorthat prints"Entry granted."if either condition isTrueand"Entry denied."if neither is. Write a comment explaining why Python does not checkhas_ticketwhenis_vipisTrue.
Exercise 3: Real World Short Circuit
-
Task: Create three variables
is_over_18 = True,has_id = Falseandis_member = True. -
Goal: Write a conditional block using
andthat prints"Access granted."only if all three areTrue. Test all combinations and write a comment explaining at which condition Python short circuits in each case.
Don't Forget to commit and Push!