Making Decisions · practice
Choose Between Two Paths
An
Sometimes a program must choose exactly one of two paths. An else block provides the second path.
A choice with two outcomes
Run this example:
Python evaluates temperature < 10 once.
If the condition is
True, the first indented block runs.If the condition is
False, theelseblock runs.
Exactly one of those two blocks runs. The final print call is outside both blocks, so it runs afterward in either case.
Change temperature to 16 and run the example again. The first message is skipped and the else message appears.
How if and else line up
The if and else keywords must have the same indentation:
if condition:
# Runs when the condition is true
else:
# Runs when the condition is false
The colon after else is required. else does not have its own condition because it means “in every other case.”
This is not valid Python:
else temperature >= 10:
If you need to check another condition, you will learn the elif keyword in the next lesson.
Use else instead of asking the opposite question
You could write two separate decisions that ask opposite questions:
For a true two-way choice, if and else express the relationship more clearly:
The second version asks one question and guarantees one result. It also avoids the risk of changing one comparison later but forgetting to update its opposite.
Store a result in each branch
Branches can
Whichever branch runs assigns a booking_status. The print call comes after the complete decision and uses the
This pattern is useful when the program needs to choose data first and display or use it afterward.
A Boolean variable works here too
The condition can be a
There is no need to write notifications_enabled == True. The variable already contains the Boolean answer.
Which version correctly connects an else block to its if statement?
# Version A
if score >= 50:
print("Passed")
else:
print("Try again")
# Version B
if score >= 50:
print("Passed")
else:
print("Try again")
What does this code print?
points = 7
if points >= 10:
print("Target reached")
else:
print("Keep going")
print("Checked")Build a booking message
The exercise gives you a fixed number of remaining seats. Use one if/else statement to assign booking_message:
use
Seats are available.whenseats_remainingis greater than0;otherwise, use
Sold out..
The supplied print calls display the chosen message and then confirm that the check is complete. After your solution passes, change seats_remaining to a positive number and run it again to see the other path.
Task
Use one else statement to choose the booking message.
If
seats_remainingis greater than0,Seats are available.tobooking_message.Otherwise, assign
Sold out.tobooking_message.
Keep the fixed if and else, and indent each assignment by four spaces.