Lesson 14: Making Decisions (if, elif, else)
Learn Python if statements, else and elif logic, code indentation, and validation patterns for handling multiple conditions effectively in programs.
Introduction
You've learned how to store data in variables and lists. You've learned how to perform calculations and manipulate strings. But so far, your programs do the same thing every time they run.
Real workflows aren't like that. You need to check conditions and respond accordingly.
Is this room compliant with code? If yes, approve it. If no, flag it for review.
Is this sheet issued? If yes, skip it. If no, process it.
This is what control flow does — it lets your code make decisions based on conditions. The primary tool for this is the if statement.
This lesson covers all forms of conditional logic: if, else, and elif. We'll build from simple checks to complex decision trees.
Lesson Overview
This section contains a general overview of topics you will learn in this lesson.
- Writing basic if statements
- Adding else blocks for two outcomes
- Using elif for multiple conditions
- Understanding code blocks and indentation
- Common patterns in architectural validation
Basic if Statements
An if statement checks a condition. If the condition is True, the indented code block runs. If False, it's skipped.
room_area = 420
if room_area >= 400:
print("Room meets minimum area requirement")
If room_area is 420, the condition room_area >= 400 is True, so the print statement executes.
If room_area is 350, the condition is False, so nothing prints.
The Syntax
if condition:
# code block (indented)
# this runs if condition is True
Key points:
- The condition must evaluate to
TrueorFalse - The colon
:is required - The code block must be indented (4 spaces or 1 tab)
- If the condition is
False, the block is skipped entirely
Indentation Matters
Python uses indentation to define code blocks. This is different from many other languages that use curly braces {}.
room_area = 420
if room_area >= 400:
print("Room is compliant")
print("Approved for construction")
print("Check complete")
The first two print statements are inside the if block (indented). They only run if the condition is true.
The last print statement is outside the block (not indented). It runs regardless.
Output (when room_area = 420):
Room is compliant
Approved for construction
Check complete
Output (when room_area = 350):
Check complete
Architectural Example: Room Compliance
room_area = 380
minimum_area = 400
if room_area < minimum_area:
print(f"Warning: Room area {room_area}m² is below minimum {minimum_area}m²")
Output:
Warning: Room area 380m² is below minimum 400m²
If the room meets the requirement, nothing prints. Sometimes that's what you want — only flag problems.
Adding else: Two Outcomes
Often you need to handle both cases: what happens if the condition is true, AND what happens if it's false.
room_area = 420
if room_area >= 400:
print("Room is compliant")
else:
print("Room is too small")
Now there are two possible paths:
- If
room_area >= 400isTrue: "Room is compliant" - If
room_area >= 400isFalse: "Room is too small"
One or the other always executes. Never both.
The Syntax
if condition:
# runs if condition is True
else:
# runs if condition is False
The else block is optional. Use it when you need to handle both outcomes.
Architectural Example: Sheet Status
sheet_status = "Draft"
if sheet_status == "Issued":
print("Sheet is approved for construction")
else:
print("Sheet needs review before issue")
Output:
Sheet needs review before issue
This explicitly handles both cases: issued sheets and everything else.
Multiple Conditions: elif
What if you have more than two possibilities?
You could write multiple if statements:
room_area = 450
if room_area < 400:
category = "Too Small"
if room_area >= 400 and room_area < 500:
category = "Standard"
if room_area >= 500 and room_area < 700:
category = "Large"
if room_area >= 700:
category = "Oversized"
This works, but it's inefficient. Every if is checked even after you've found the answer.
Better: use elif (else if).
room_area = 450
if room_area < 400:
category = "Too Small"
elif room_area < 500:
category = "Standard"
elif room_area < 700:
category = "Large"
else:
category = "Oversized"
print(category) # Output: Standard
How elif Works
elif means "else if" — if the previous conditions were false, check this one.
Python checks conditions in order:
- Is
room_area < 400? No (450 is not < 400) - Is
room_area < 500? Yes (450 < 500) - Execute that block, skip the rest
Once one condition is true, the rest are ignored. This is efficient and prevents overlap.
The Syntax
if condition_1:
# runs if condition_1 is True
elif condition_2:
# runs if condition_1 is False and condition_2 is True
elif condition_3:
# runs if previous conditions are False and condition_3 is True
else:
# runs if all conditions are False
You can have as many elif blocks as needed. The else at the end is optional but common — it catches everything that didn't match.
Order Matters
The order of conditions matters because Python stops at the first True condition.
room_area = 450
# Correct order
if room_area < 400:
category = "Too Small"
elif room_area < 500:
category = "Standard"
elif room_area < 700:
category = "Large"
else:
category = "Oversized"
print(category) # Output: Standard
If you reverse the order:
# Wrong order
if room_area < 700:
category = "Large" # This catches 450!
elif room_area < 500:
category = "Standard" # Never reached
Here, 450 < 700, so it's categorized as "Large" and the Standard check never runs.
Rule: Order conditions from most specific to least specific, or from smallest to largest ranges.
Architectural Example: Floor Classification
floor_number = 0
if floor_number < 0:
floor_type = "Basement"
elif floor_number == 0:
floor_type = "Ground Floor"
elif floor_number <= 3:
floor_type = "Lower Floors"
elif floor_number <= 10:
floor_type = "Mid Floors"
else:
floor_type = "Upper Floors"
print(f"Floor {floor_number}: {floor_type}")
# Output: Floor 0: Ground Floor
When to Use Each Form
Just if: Use when you only care about one case (usually flagging problems).
if area < minimum:
print("Warning: Area too small")
if-else: Use when you have exactly two outcomes.
if status == "Issued":
print("Approved")
else:
print("Not approved")
if-elif-else: Use when you have multiple distinct possibilities.
if area < 400:
category = "Small"
elif area < 600:
category = "Medium"
else:
category = "Large"
Real Architectural Workflows
Example 1: Room Validation
room_area = 380
room_height = 2.6
minimum_area = 400
minimum_height = 2.7
# Check area
if room_area < minimum_area:
print(f"Area violation: {room_area}m² (minimum: {minimum_area}m²)")
# Check height
if room_height < minimum_height:
print(f"Height violation: {room_height}m (minimum: {minimum_height}m)")
# Output:
# Area violation: 380m² (minimum: 400m²)
# Height violation: 2.6m (minimum: 2.7m)
Example 2: Sheet Status Categorization
sheet_status = "Draft"
if sheet_status == "Issued":
action = "Send to contractor"
elif sheet_status == "Approved":
action = "Prepare for issue"
elif sheet_status == "In Review":
action = "Wait for approval"
elif sheet_status == "Draft":
action = "Continue design work"
else:
action = "Unknown status - check manually"
print(f"Action: {action}")
# Output: Action: Continue design work
Example 3: Priority Assignment
issue_severity = "Critical"
if issue_severity == "Critical":
priority = 1
deadline = "24 hours"
elif issue_severity == "High":
priority = 2
deadline = "3 days"
elif issue_severity == "Medium":
priority = 3
deadline = "1 week"
else:
priority = 4
deadline = "2 weeks"
print(f"Priority: {priority}, Deadline: {deadline}")
# Output: Priority: 1, Deadline: 24 hours
Common Mistakes
Forgetting the colon
if room_area >= 400 # Missing colon
print("Compliant")
# SyntaxError: invalid syntax
The colon is required. It signals the start of the code block.
Wrong indentation
if room_area >= 400:
print("Compliant") # Not indented
# IndentationError: expected an indented block
The code block must be indented. Use 4 spaces (or 1 tab, but be consistent).
Using = instead of ==
if room_area = 400: # Wrong - this is assignment
print("Compliant")
# SyntaxError: invalid syntax
Use == for comparison, not = (which is assignment).
Overlapping elif conditions
room_area = 450
if room_area < 500:
category = "Small"
elif room_area < 600: # Never reached if area is 450
category = "Medium"
If 450 < 500, the first condition is true, so the second is never checked. Order your conditions carefully.
Missing else when you need it
status = "Unknown"
if status == "Issued":
action = "Send to contractor"
elif status == "Draft":
action = "Continue work"
print(action)
# Error: UnboundLocalError (if status is neither)
If status is something else, action is never defined. Add an else to catch unexpected values:
if status == "Issued":
action = "Send to contractor"
elif status == "Draft":
action = "Continue work"
else:
action = "Check status manually"
Assignment
- Create a new file called
conditionals.py - Room area validator:
- Create variables:
room_area = 380,minimum_area = 400 - Write an if statement that prints a warning if the room is too small
- Create variables:
- Add an else block:
- Print "Room is compliant" if it meets the requirement
- Sheet status checker:
- Variable:
sheet_status = "Draft" - Use if-elif-else to print an action for each status:
- "Issued" → "Send to contractor"
- "Approved" → "Prepare for issue"
- "Draft" → "Continue work"
- Anything else → "Unknown status"
- Variable:
- Room categorization:
- Variable:
room_area = 520 - Use if-elif-else to categorize:
- < 400: "Too Small"
- < 500: "Standard"
- < 700: "Large"
- = 700: "Oversized"
- Print the category
- Variable:
- Floor classification:
- Variable:
floor_number = 5 - Categorize:
- < 0: "Basement"
- == 0: "Ground"
- 1-3: "Lower"
- 4-10: "Mid"
- 10: "Upper"
- Variable:
- Real scenario - Compliance checker:
- Variables:
area = 420,height = 2.6 - Minimums:
min_area = 400,min_height = 2.7 - Check both conditions
- If both pass: "Compliant"
- If either fails: print which one(s) failed
- Variables:
- Experiment:
- Try an if statement without a colon (see the error)
- Try a code block without indentation (see the error)
- Use
=instead of==in a condition (see the error) - Write elif conditions in wrong order and see what happens
Knowledge Check
The following questions are an opportunity to reflect on key topics in this lesson.
- <a class="knowledge-check-link" href="#basic-if-statements">What does an if statement do?</a>
- <a class="knowledge-check-link" href="#indentation-matters">Why does indentation matter in Python?</a>
- <a class="knowledge-check-link" href="#adding-else-two-outcomes">What does an else block do?</a>
- <a class="knowledge-check-link" href="#multiple-conditions-elif">What is elif short for?</a>
- <a class="knowledge-check-link" href="#how-elif-works">What happens when one elif condition is True?</a>
- <a class="knowledge-check-link" href="#order-matters">Why does the order of conditions matter?</a>
- <a class="knowledge-check-link" href="#when-to-use-each-form">When would you use just if vs if-else vs if-elif-else?</a>
Additional Resources
This section contains helpful links to related content. It isn't required, so consider it supplemental.
- Python's official documentation on if statements provides additional details
- Real Python's guide to conditionals covers edge cases and best practices