Why this matters
Programs have to make decisions: pass or fail, discount or full price, even or odd. That is
branching, and in Python you write it with if, elif, and else. This is the code
version of the diamond you saw in a flowchart.
The idea
A comparison operator asks a yes/no question and answers with True or False:
| Operator | Means |
|---|---|
== | equal to |
!= | not equal to |
< > | less / greater than |
<= >= | less / greater than or equal |
if runs its indented block only when the condition is True. else covers the
other case. Use elif ("else if") to test more conditions in order. Python takes the
first branch whose condition is true and skips the rest.
if condition:
# runs when condition is True
elif other_condition:
# runs when the first was False and this is True
else:
# runs when none above were True
Picture it
flowchart TD
A([Start: score]) --> B{score >= 90?}
B -- Yes --> C[grade = A]
B -- No --> D{score >= 50?}
D -- Yes --> E[grade = B]
D -- No --> F[grade = C]
C --> G([print grade])
E --> G
F --> G
Worked example
x = 70
if x >= 90:
result = 'Grade is A'
elif x >= 50:
result = 'Grade is B'
else:
result = 'Grade is C'
print(result) # Grade is B
x >= 90 is False, so Python checks the next condition. x >= 50 is True, so it takes
that branch and ignores else.
Your turn
Predict which branch a program takes, then write functions that classify their input with
if / elif / else.
Recap
- Comparison operators give
TrueorFalse. ifruns when its condition is true;elseis the fallback.elifadds more cases; the first true branch wins.