Teach your program to choose. Branch with if, elif and else, understand truthiness, and meet the match statement.
By the end of today you can
- Write if, elif and else blocks with correct indentation
- Order conditions so the right branch runs
- Predict which values count as True or False
- Choose between options with match
- Write a one-line conditional expression
So far your programs ran every line, top to bottom. Real programs make decisions: show a discount if the cart is big enough, or an error if a password is too short. That's what if is for.
if, elif, else
Change score and run it again. Three rules to remember:
- Each condition line ends with a colon
:. - The code that belongs to a branch is indented, by 4 spaces by convention.
- Python checks branches top to bottom and runs only the first one that's
True.elseruns when none of them are.
Indentation is the syntax
Python has no curly braces around blocks; indentation is the structure. Mixing indentation levels causes an IndentationError:
Combining conditions
Use and, or and not from Day 4 inside a condition:
Truthiness: what counts as True?
An if doesn't need a comparison. Python treats every value as truthy or falsy:
| Falsy (act like False) | Truthy (act like True) |
|---|---|
False, None | True |
0, 0.0 | Any other number, like -1 or 3.5 |
"" (empty string) | Any non-empty string, even "False" |
[], {}, () (empty collections) | Collections with at least one item |
Nested decisions
An if can sit inside another one. Keep nesting shallow, because two levels is already plenty:
match: choosing between many options
When you compare one value against several fixed options, match (Python 3.10+) is often clearer than a long elif chain:
| means "or", and case _ matches anything else, like else.
One-line conditional expression
For a simple either/or value, use the conditional expression A if condition else B:
Recap
if/elif/elsebranch on conditions; only the first true branch runs.- Lines ending with
:start a block; the block is defined by indentation. - Empty values (
0,"",[],None) are falsy; almost everything else is truthy. matchpicks between fixed options;x if cond else ychooses a value in one line.
Knowledge check
Test what you learned
4 questions · pick an answer to see if you're right
- 1
How does Python know which lines belong inside an if block?
- 2
score = 85. With branches "if score >= 60", then "elif score >= 80", then "else", which branch runs?
- 3
Which of these values is truthy?
- 4
What does this print? x = 7, then print("even" if x % 2 == 0 else "odd")
Finished today's lesson?