if Statements
Grant admin access only if credentials match. Charge shipping fees based on order total and destination. Display different error messages depending on what went wrong. Calculate letter grades from numeric scores. Route HTTP requests to different handlers based on the URL path.
Every one of these requires your program to choose between different paths of execution. That's what if statements enable: conditional logic that makes programs adaptive, responsive, and intelligent. They're the foundation of control flow—the ability to make decisions based on conditions.
What is an If Statement?
An if statement evaluates a boolean condition and executes a block of code only when that condition is True:
- The condition
age >= 18evaluates toTrueorFalse—ifTrue, the indented block executes
You can extend this with elif (else if) to check multiple conditions in sequence, and else to handle cases where none of the conditions matched:
| If-Elif-Else Structure | |
|---|---|
- Checks the first condition—if
True, prints "A" and skips the rest - Only evaluated if the previous
ifwasFalse—checks conditions in order - The fallback—executes only if all previous conditions were
False
Why If Statements Matter
If statements transform static code into adaptive programs:
- Access control: Check permissions before allowing operations—authentication, authorization, admin features
- Input validation: Verify data meets requirements before processing—email format, password strength, age restrictions
- Error handling: Different responses based on what went wrong—404 vs 500 errors, network failures vs invalid input
- Business logic: Calculate pricing, apply discounts, determine shipping costs based on complex rules
- State management: Different behavior based on current state—game over vs playing, logged in vs logged out
- Data filtering: Include or exclude items based on criteria—search results, active users, valid transactions
Without conditional logic, every program would execute the same way every time. If statements enable programs to respond to their environment.
Common Patterns
Simple If-Else: Binary Decisions
Check a score threshold. Validate user age. Test if a file exists—any yes/no decision:
| Game Win Condition | |
|---|---|
- Simple comparison—
Trueif player has reached or exceeded the threshold - F-string calculates the remaining points needed—output: "You need 53 more points to win!"
Combining Conditions: AND/OR Logic
Authenticate users. Check multiple requirements. Validate complex eligibility—combine boolean operators:
- Both conditions must be
True—the backslash (\) continues the line for readability. You could also write this on one line or use parentheses.
Multiple Conditions: If-Elif-Else Chains
Grade assignment. Tax brackets. Shipping zones. Priority levels—sequential condition checking:
| Grade Calculation | |
|---|---|
- Python checks conditions from top to bottom—first match wins
- Only checked if the
if(and any precedingelif) failed—order matters! - The catch-all—executes if no previous condition matched
Nested Conditionals
Check driver eligibility (age, license, insurance). Process payments (valid card, sufficient funds, fraud check). Validate forms (all fields present, correct format, unique email). Sometimes one decision leads to another:
| Nested If Statements | |
|---|---|
- Three levels of nesting—each decision depends on the previous one being
True
While nesting works, too many levels make code hard to follow. Flatten with boolean operators or use guard clauses in functions:
| Flattened Conditionals | |
|---|---|
- Single condition combining all requirements—easier to read and test
Avoid Deep Nesting
Nesting more than 2-3 levels deep usually signals a need to refactor. Extract functions, combine conditions with and/or, or use early returns.
The Ternary Operator (Conditional Expression)
Set default values. Format output based on a condition. Assign variables conditionally in one line—the ternary operator handles simple either/or logic concisely:
| Ternary Operator Basics | |
|---|---|
- Syntax:
value_if_true if condition else value_if_false—condition is evaluated, then one of the two values is returned
| Practical Ternary Examples | |
|---|---|
- If
user_inputis truthy, use it; otherwise default to "Anonymous"—leverages truthiness - Binary decision—pass/fail based on threshold
- Multiple conditions chained—works but quickly becomes hard to read
When to Avoid Ternaries
Ternary expressions are elegant for simple either/or logic. Chaining them (nested ternaries) sacrifices readability. If you need multiple conditions, use if-elif-else instead. PEP 8 emphasizes: "Readability counts."
Match Statements (Python 3.10+)
Parse HTTP status codes. Route commands. Handle event types. Process structured data. Python 3.10 introduced match statements—pattern matching that goes far beyond simple equality checks:
| Basic Match Statement | |
|---|---|
- The
matchstatement evaluatesstatusonce, then checks it against eachcasepattern - The underscore (
_) is a wildcard—matches anything not caught by previous cases (likeelsein if-elif-else)
Matching Multiple Values
Weekend vs weekday logic. Categorizing user roles. Grouping similar cases—the pipe operator (|) matches any of several values:
| Matching Multiple Values | |
|---|---|
- The pipe (
|) operator means "or"—matches if the value equals any of the options listed
Matching with Guards
Categorize numbers by properties. Filter data based on conditions. Add complex validation—guards combine pattern matching with conditional logic:
- The
ifafter the pattern is a guard—pattern matches any value, but only proceeds ifn < 0 - Exact value match—no guard needed for simple equality
Matching Sequences and Structures
Parse command strings. Process API responses. Route structured data. Destructure tuples and lists—match excels at pattern matching complex data:
- Splits the string into a list, then matches against list patterns
- Matches a 2-element list where first element is "hello"—second element is captured in variable
name
- Matches dictionaries with specific keys—values are captured into variables
When to Use Match vs If-Elif
match excels at:
- Handling multiple specific values (HTTP status codes, command types, state values)
- Destructuring complex data structures (lists, dicts, tuples from APIs or parsed data)
- Making state machines and command parsers more readable
- Pattern matching with guards for complex filtering
Use if-elif-else for:
- Simple boolean conditions and range checks
- Code that needs to run on Python <3.10
- When you don't need destructuring or pattern matching
Practice Problems
Practice Problem 1: Basic If-Else
What will this code print?
temperature = 25
if temperature > 30:
print("Hot")
elif temperature > 20:
print("Warm")
else:
print("Cold")
Answer
It prints "Warm".
The first condition (temperature > 30) is False (25 is not greater than 30). Python then checks the elif condition (temperature > 20), which is True (25 > 20), so it prints "Warm" and skips the else block.
Practice Problem 2: Ternary Operator
Rewrite this if-else block as a ternary expression:
Practice Problem 3: Nested vs Flattened
Why is the second version better than the first?
# Version 1
if age >= 18:
if has_id:
if not is_banned:
print("Entry allowed")
# Version 2
if age >= 18 and has_id and not is_banned:
print("Entry allowed")
Answer
Version 2 is better because:
- Readability: Single line condition is easier to understand than 3 levels of nesting
- Maintainability: Easier to modify or add conditions
- Pythonic: Combining conditions with
and/oris idiomatic Python
Version 1 forces you to track indentation levels to understand the logic. Version 2 makes all requirements explicit in one place.
Practice Problem 4: Match Statements
What does this match statement do differently than an if-elif chain?
match command.split():
case ["move", direction, steps]:
move(direction, int(steps))
case ["quit"]:
exit()
Answer
The match statement destructures the list and captures values into variables.
["move", direction, steps]matches a 3-element list where the first element is "move", then captures the second and third elements intodirectionandstepsvariables- An if-elif chain would need manual indexing:
if parts[0] == "move": direction = parts[1]; steps = parts[2]
This destructuring makes parsing structured data much cleaner than traditional conditionals.
Key Takeaways
| Concept | What to Remember |
|---|---|
| if-elif-else | The workhorse of decision-making |
| Nested conditionals | Useful but flatten when possible |
| Ternary operator | value_if_true if condition else value_if_false |
| match (3.10+) | Pattern matching with destructuring |
Wildcard _ |
Matches anything in match statements |
| Guards | Add if conditions to match cases |
Further Reading
- Python If Statements Documentation - Official tutorial on conditional statements
- PEP 622 – Structural Pattern Matching - The proposal that introduced match statements in Python 3.10
- PEP 634 – Structural Pattern Matching: Specification - Complete specification for match syntax
- PEP 8 – Style Guide - Best practices for writing conditionals
- Computational Thinking - Understanding control flow and decision-making in algorithms
Conditionals are the decision-making heart of every program. Without them, code executes linearly, the same way every time—deterministic but inflexible. if statements introduce adaptability, enabling programs to respond to data, user input, and changing conditions.
Master the fundamentals: if-elif-else for sequential conditions, ternary operators for simple assignments, nested conditionals flattened with boolean logic. Then level up with Python 3.10's match statements—pattern matching that destructures data structures elegantly. Each approach has its place: use the simplest tool that clearly expresses your intent. Readability counts.