Control Flow: if, elif, else
Learn decision-making in Python using if, elif, and else statements. Step-by-step tutorial with hands-on exercises and edge-case troubleshooting.
Focus: control flow with if, elif, and else
Imagine your program has to make decisions: "If the user is logged in, show the dashboard; otherwise, redirect to the login page." Without a way to handle such choices, every Python script would run the same sequence of instructions, regardless of input. That's where control flow with if, elif, and else comes in — it lets your code branch based on conditions, making it dynamic, responsive, and truly useful.
The problem this lesson solves
A straight-line program executes statements one after another, top to bottom. While that works for simple calculators, real applications need to react differently depending on user input, data values, or system state. For example:
- A weather app must show "Rain" or "Sunny" depending on the forecast.
- An e-commerce site applies a discount only if the cart total exceeds $50.
- A game checks whether the player has enough health to continue.
Without conditional logic, you'd have to write separate programs for every possible outcome. That's impractical. With if, elif, and else, you write one program that chooses the right path at runtime.
Core concept / mental model
Think of an if statement as a fork in the road. Your program reaches a decision point, evaluates a condition (a Boolean expression), and takes one branch or the other. elif (short for "else if") adds more forks. else catches everything that doesn't match earlier conditions.
Here's the Python syntax in plain English:
if condition_1:
do_this()
elif condition_2:
do_that()
else:
do_default()
Pro tip: Indentation is meaningful in Python — each branch must be indented consistently (usually 4 spaces). Python will raise an
IndentationErrorif you mix tabs and spaces or forget to indent.
How Python evaluates conditions
A condition is any expression that yields a Boolean (True or False). Python checks the first if, then each elif in order, and stops at the first True branch. If all conditions are False, the else block runs (if present).
Truthiness in Python
Not everything needs a direct Boolean comparison. Python treats the following as False in a condition:
- None
- 0, 0.0, 0j
- Empty sequences: '', [], (), {}, set()
- range(0)
Everything else is True. This is called truthiness and lets you write concise checks like if user: instead of if user is not None:.
How it works step by step
Step 1: Write a simple if
The most basic form checks one condition and optionally runs code when True.
temperature = 30
if temperature > 25:
print("It's hot outside!")
Step 2: Add an else
To handle the "otherwise" case, attach an else block.
temperature = 15
if temperature > 25:
print("It's hot outside!")
else:
print("It's not hot today.")
Step 3: Chain multiple conditions with elif
When you have more than two alternatives, use one or more elif blocks. The order matters — Python evaluates top to bottom and stops at the first match.
temperature = 20
if temperature > 35:
print("Extreme heat!")
elif temperature > 25:
print("It's warm.")
elif temperature > 15:
print("It's mild.")
else:
print("It's cold.")
If temperature is 20, only "It's mild." prints — the earlier elif temperature > 25 is False, and the else never fires because a previous elif matched.
Step 4: Nest if statements (carefully)
You can place if blocks inside other if blocks, but deep nesting hurts readability. Prefer combining conditions with and, or, and not.
# Nested version (harder to read)
if user.logged_in:
if user.role == 'admin':
print("Welcome, admin!")
else:
print("Welcome, user!")
# Flat version (easier)
if user.logged_in and user.role == 'admin':
print("Welcome, admin!")
elif user.logged_in:
print("Welcome, user!")
Hands-on walkthrough
Let's build a real-world example: a grade checker and a menu system.
Example 1: Grade assignment
Given a numeric score, return a letter grade.
score = 87
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Score {score} → Grade {grade}")
Output: Score 87 → Grade B
Example 2: Interactive menu with input
This script lets the user choose an option and validates the input.
user_input = input("Choose: 1) Greeting 2) Joke 3) Exit: ")
if user_input == "1":
print("Hello! Welcome to Python.")
elif user_input == "2":
print("Why did the programmer quit his job? Because he didn't get arrays.")
elif user_input == "3":
print("Goodbye!")
else:
print("Invalid option. Please enter 1, 2, or 3.")
Example 3: Checking multiple conditions with and
username = "alice"
password = "secret123"
if username == "admin" and password == "pass123":
print("Administrator access granted.")
elif username == "alice" and password == "secret123":
print("Welcome back, Alice!")
else:
print("Login failed.")
Compare options / when to choose what
| Structure | When to use | Example |
|---|---|---|
if alone |
One condition to check, no alternative | if error: log_error() |
if/else |
Binary choice — on/off, yes/no | if valid: accept else: reject |
if/elif/else |
Three or more mutually exclusive branches | grade letter or menu option |
Nested if |
Conditions are hierarchical (use sparingly) | if logged_in: if role: |
if with and/or |
Combine multiple independent conditions | if age >= 18 and has_id: |
Pro tip: Avoid
elifchains longer than 5–6 branches — consider using a dictionary mapping or Python'smatchstatement (Python 3.10+) for complex dispatch logic.
Alternative approaches:
- Dictionary dispatch: Map keys to functions or values. Faster than elif chains for 5+ options.
- Ternary expression: x if condition else y for simple inline assignments — use sparingly to avoid readability loss.
Troubleshooting & edge cases
Common mistakes
1. Forgetting the colon after if, elif, or else
if x > 0
print("Positive")
# SyntaxError: invalid syntax
2. Missing indentation or mixed indentation
if x > 0:
print("Positive") # IndentationError
3. Using assignment = instead of comparison ==
if user = "admin": # This does NOT compare — it assigns!
...
# TypeError: cannot assign to function call
4. Wrong order of conditions
x = 95
if x > 50:
print("Above average")
elif x > 90:
print("Excellent!") # Never reached!
Always place more specific conditions before general ones.
5. Using elif without a preceding if
elif x > 0: # SyntaxError — no if before it
...
Edge cases
- Empty
ifbody: Usepassas a placeholder if you need an empty block. - Floating-point comparisons: Due to precision, avoid
==on floats; useabs(a - b) < 1e-9. - Overlapping conditions: Ensure conditions don't accidentally match more than one branch (unless intended).
What you learned & what's next
You now understand:
- How to make decisions in Python using
if,elif, andelse - How Python evaluates conditions using truthiness
- How to combine conditions with
and,or, andnot - How to avoid common pitfalls like missing colons and wrong condition order
- When to choose
if/elif/elseover alternatives like dictionary dispatch
This is the foundation for all decision-making in Python. Next, you'll explore loops — for and while — which let you repeat actions automatically. Together, conditionals and loops form the core of dynamic, responsive Python programs.
Practice recap
Write a Python script that asks the user for their age and prints a message: if under 13, say 'Child'; if 13–17, 'Teenager'; if 18–64, 'Adult'; else 'Senior'. Test with edge cases like negative numbers or non-numeric input (hint: use try/except from a later lesson, or just handle it with conditionals). Try adding a second condition that also checks if the user has a valid ID.
Common mistakes
- Forgetting the colon at the end of
if,elif, orelselines — Python raises aSyntaxError. - Mixing tabs and spaces for indentation — causes
IndentationError; stick to 4 spaces. - Using assignment
=instead of comparison==inside a condition — assigns a value and often leads to unexpected behavior orTypeError. - Placing a general condition before a specific one in an
elifchain — the specific branch becomes unreachable. - Having an
eliforelsewithout a precedingif— results in aSyntaxError.
Variations
- Use a dictionary mapping to avoid long
elifchains — e.g.,{'A': 90, 'B': 80}with a fallback function. - Use Python's ternary expression (
x if condition else y) for simple, single-line assignments. - For Python 3.10+, use the
matchstatement for pattern matching on more complex structures like tuples or classes.
Real-world use cases
- Validating user input in a web form — e.g., checking email format and password strength before submission.
- Routing HTTP requests in a web framework — e.g.,
if path == '/home'vselif path == '/login'. - Determining discounts in an e-commerce checkout — apply tiered discounts based on cart total and membership level.
Key takeaways
- Control flow with
if,elif, andelselets your program make decisions based on Boolean conditions. - Python uses truthiness — empty values, zero, and
Noneevaluate toFalse; everything else isTrue. - The order of conditions matters: place more specific branches before general ones in an
elifchain. - Use
and,or, andnotto combine multiple conditions; prefer them over deep nesting. - Common syntax errors include missing colons, incorrect indentation, and using
=instead of==. - For many options (5+), consider dictionary dispatch or the
matchstatement instead of longelifchains.
Keep learning
Related tutorials, quizzes, and articles for this topic.
Discussion
Questions, corrections, and tips help everyone reading this page.
0 comments
Add a comment
No comments yet — start the thread.