Making Decisions: if / elif / else
Lesson 5 of 7 · View course roadmap
Learn the idea
Programs become intelligent when they can choose. Python decides with if, elif and else:
Comparison operators produce booleans: == (equal), != (not equal), <, >, <=, >=. Combine conditions with and, or, not.
Indentation is the syntax. The indented block under an if only runs when the condition is True. Python convention is 4 spaces.
if: checked firstelif: checked only if everything above was False (you can chain many)else: the fallback, runs if nothing matched
Where you'll use this
Every access check ('is this user an admin?'), price rule ('free shipping over €50') and form validation in every app you use is an if/elif chain. Reading them fluently is reading business logic.
Common mistakes
- Using
=instead of==in a condition: Python catches this as a SyntaxError, unlike C. - Forgetting the colon at the end of
if/elif/elselines. - Inconsistent indentation: mixing tabs and spaces breaks the block structure. Configure your editor to insert 4 spaces per Tab.
- Chaining that never triggers: checking
score >= 80beforescore >= 90means the 90 branch is unreachable.
Pro tip
Python chains comparisons naturally: 18 <= age < 65 works exactly like the math notation. Also, empty containers are falsy: 'if my_list:' is the Pythonic way to test non-emptiness.
Watch how it runs line by line
Press play to watch Python execute this code, one line at a time.
Try it yourself
The lesson example is loaded and ready: press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.
Output appears here…
Pass the challenge +25 XP
The starter defines temperature = 31. Print Hot if it is above 28, Mild if it is above 15 (but not hot), otherwise Cold.
Hot
Check the hottest condition first: if temperature > 28.
temperature = 31
if temperature > 28:
print("Hot")
elif temperature > 15:
print("Mild")
else:
print("Cold")
Run your code to check it…
Check your understanding
Your notes (saved on this device)
Tip: use ← and → to move between lessons, ⌘K to search everything.