02.1 - Conditional Statements: if, elif, else
The if Statement
The if statement executes a block of code only if a condition is True.
age = 18
if age >= 18:
print("You are an adult") # indented block — 4 spaces
# Python uses INDENTATION (not braces) to define blocks
⚠️ Python uses indentation (4 spaces) to define code blocks. This is mandatory, not optional.
┌─────────────────────────────────────────────┐
│ if condition: │
│ ┌──────────────────────────────────┐ │
│ │ block executed when True │ │
│ └──────────────────────────────────┘ │
│ # code continues here (always executed) │
└─────────────────────────────────────────────┘
if / else
score = 75
if score >= 60:
print("Pass ✅")
else:
print("Fail ❌")
if / elif / else
elif (else if) chains multiple conditions. Only the first matching branch executes.
score = 82
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"Grade: {grade}") # Grade: B
Compound Conditions
Combine conditions with and, or, not:
age = 25
has_license = True
is_drunk = False
# All conditions must be True
if age >= 18 and has_license and not is_drunk:
print("You can drive")
# Range check (Python allows chaining)
temperature = 22
if 18 <= temperature <= 26:
print("Comfortable temperature")
# Equivalently
if temperature >= 18 and temperature <= 26:
print("Comfortable temperature")
Nested if Statements
role = "admin"
is_active = True
if role == "admin":
if is_active:
print("Full access granted")
else:
print("Account suspended")
else:
print("Limited access")
Tip: Deeply nested if statements are hard to read. Prefer guard clauses (early returns).
Guard Clauses (Early Return Pattern)
Guard clauses exit early to reduce nesting — a key professional Python pattern:
# ❌ Deep nesting — hard to read
def process_order(order):
if order is not None:
if order["status"] == "paid":
if order["items"]:
return "Processing"
else:
return "Empty order"
else:
return "Not paid"
else:
return "No order"
# ✅ Guard clauses — flat and readable
def process_order(order):
if order is None:
return "No order"
if order["status"] != "paid":
return "Not paid"
if not order["items"]:
return "Empty order"
return "Processing"
Ternary Expression (Conditional Expression)
A compact single-line if/else:
# Syntax: value_if_true if condition else value_if_false
status = "adult" if age >= 18 else "minor"
# Equivalent to:
if age >= 18:
status = "adult"
else:
status = "minor"
# Common use cases
max_val = a if a > b else b
label = "even" if n % 2 == 0 else "odd"
message = "Welcome back!" if user else "Please log in"
Use ternary for simple assignments — not for complex logic.
match / case (Python 3.10+)
match is Python's structural pattern matching — a modern alternative to long elif chains:
command = "quit"
match command:
case "help":
print("Available commands: start, stop, quit")
case "start":
print("Starting...")
case "stop":
print("Stopping...")
case "quit" | "exit": # multiple patterns
print("Goodbye!")
case _: # default (wildcard)
print(f"Unknown command: {command}")
Matching with Conditions (Guards)
point = (3, 0)
match point:
case (0, 0):
print("Origin")
case (x, 0):
print(f"On X-axis at {x}")
case (0, y):
print(f"On Y-axis at {y}")
case (x, y) if x == y:
print(f"On diagonal at {x}")
case (x, y):
print(f"Point at ({x}, {y})")
Comparison Table
| Structure | Use case |
|---|---|
if/elif/else | General conditions, any Python version |
Ternary x if c else y | Single-line value assignment |
match/case | Matching against specific values/patterns (Python 3.10+) |
| Guard clauses | Early returns to reduce nesting |
Key Vocabulary
| Term | Definition |
|---|---|
| Conditional | A statement that executes code based on a boolean condition |
| Indentation | Mandatory 4-space block definition in Python (no braces) |
| elif | "Else if" — chains multiple conditions |
| Guard clause | An early return that handles edge cases first |
| Ternary expression | value_if_true if condition else value_if_false |
match/case | Python 3.10+ structural pattern matching |
| Truthiness | Whether an expression evaluates to True in a boolean context |
Summary
if / elif / elsecontrols execution based on boolean conditions- Python uses 4-space indentation to define blocks — no curly braces
- Combine conditions with
and,or,not; chain ranges witha < x < b - Guard clauses (early returns) flatten nested code and improve readability
- Ternary expressions
x if cond else yare compact single-line conditionals match/case(Python 3.10+) cleanly handles multiple fixed values
📄️ 02.1 - Conditional Statements
Control program execution with if/elif/else, match/case, ternary expressions, and guard clauses
📄️ 02.2 - Loops: for & while
Master Python iteration with for loops, while loops, range(), enumerate(), zip(), and loop control statements
📄️ 02.3 - Comprehensions
Write concise, Pythonic data transformations with list comprehensions, dict comprehensions, set comprehensions, and generator expressions
📄️ Lab - Module 02
Build a complete number guessing game using conditions, loops, and comprehensions
📄️ Quiz - Module 02
30 questions on conditions, loops, break/continue, and comprehensions