Control Flow: Conditional Statements (if, elif, else) and Match-Case
A script that runs the exact same lines blindly from top to bottom cannot respond to changing conditions. Real programmes need to make decisions: escalate an incident if response time exceeds a threshold, reject a password if it is too short or route an HTTP status code to the right recovery handler. In Python, you direct these decisions using conditional statements (if, elif, else) and structural pattern matching (match-case).
How if, elif and else Work
Python evaluates conditions top-to-bottom and runs the indented code block under the first condition that evaluates to True:
cpu_load = 88
if cpu_load >= 90:
print("CRITICAL: Page on-call engineer immediately.")
elif cpu_load >= 75:
print("WARNING: High CPU utilisation detected.")
else:
print("OK: System operating within normal thresholds.")
Comparison and Logical Operators
| Operator | Meaning | Example (Evaluates to True) |
|---|---|---|
== / != |
Equal to / Not equal to | status_code == 200 |
<, <=, >, >= |
Less than, less than or equal, greater than, greater than or equal | retry_count <= 3 |
and |
Both conditions must be True |
is_admin and is_authenticated |
or |
At least one condition must be True |
role == "owner" or role == "editor" |
not |
Inverts a boolean value | not is_locked |
is / is not |
Identity check (used for checking None) |
assigned_owner is None |
Truthy and Falsy Values in Python
Falsy Values (Evaluate to False) |
Truthy Values (Evaluate to True) |
|---|---|
False and None |
True |
Zero of any numeric type: 0, 0.0 |
Any non-zero number: 1, -5, 0.01 |
Empty string: "" |
Any non-empty string: "ok", " " |
Empty collections: [], (), {}, set() |
Any collection with at least one element |
Structural Pattern Matching (match-case)
Introduced in Python 3.10, match-case provides a clean alternative to long chains of elif statements when comparing a value against specific patterns:
http_status = 503
match http_status:
case 200 | 201:
action = "Request succeeded."
case 401 | 403:
action = "Authentication failure—check API token."
case 404:
action = "Endpoint not found—verify URL path."
case 500 | 502 | 503:
action = "Server error—trigger retry with backoff."
case _:
action = f"Unhandled HTTP status: {http_status}"
print(action)
A Short Example: Automated Incident Priority Router
impact = "High"
urgency = "High"
is_vip_service = True
if impact == "High" and urgency == "High":
priority = "P1 - Critical"
target_sla_hours = 1
elif (impact == "High" or urgency == "High") or is_vip_service:
priority = "P2 - High"
target_sla_hours = 4
elif impact == "Medium" and urgency == "Medium":
priority = "P3 - Medium"
target_sla_hours = 24
else:
priority = "P4 - Low"
target_sla_hours = 72
print(f"Assigned Priority: {priority} (Target SLA: {target_sla_hours}h)")
Common Mistakes
- Confusing assignment (
=) with equality (==):x = 10assigns a value;x == 10compares values. - Writing
if status == "open" or "pending":: Because"pending"is a non-empty string, it is always truthy! Writeif status in ("open", "pending"):instead. - Ordering numeric
elifranges backwards: Always order numeric threshold checks from highest to lowest so broad conditions do not swallow narrower ones.
Key takeaways
- Use
if,elifandelseto branch execution; Python executes only the first matching branch. - Combine conditions explicitly using
and,orandnot, and useis Nonewhen checking forNone. - Empty strings (
""), zero (0),Noneand empty collections are falsy; non-empty values are truthy. - Use
match-case(Python 3.10+) for clean multi-way branching on status codes or commands.