if, elif, and else
An if statement chooses whether a block of code runs.
The indented line runs only when the condition is True.
Indentation Defines the Block
Python uses indentation to show which lines belong to the branch:
Both indented lines belong to the if block.
This line does not:
print("done") runs no matter what.
else Handles the Other Case
Use else when you want one thing to happen if the condition is true and
another thing to happen otherwise:
Output:
try again
elif Handles More Cases
Use elif for another condition:
Python checks the conditions in order and uses the first true branch.
Ordered conditions
Change the temperature and watch which branch runs.
Ready to run.
Order Changes Which Branch Runs
Order matters. This is wrong for grading:
The first condition is already true, so Python never reaches the excellent
branch. Put the more specific condition first.
What does this print?
Answer it first, then check.
HintStop at the first true branch
Check score >= 90 before considering the elif.
SolutionThe first branch runs
92 >= 90 is True, so Python prints excellent and skips the remaining
branches.
Branches Should Be Mutually Clear
Read an if statement as a decision tree. Check each condition in order, and
pay attention to indentation.