Skip to main content

02.1 - Conditional Statements: if, elif, else

Theory 20 min Beginner

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

StructureUse case
if/elif/elseGeneral conditions, any Python version
Ternary x if c else ySingle-line value assignment
match/caseMatching against specific values/patterns (Python 3.10+)
Guard clausesEarly returns to reduce nesting

Key Vocabulary

TermDefinition
ConditionalA statement that executes code based on a boolean condition
IndentationMandatory 4-space block definition in Python (no braces)
elif"Else if" — chains multiple conditions
Guard clauseAn early return that handles edge cases first
Ternary expressionvalue_if_true if condition else value_if_false
match/casePython 3.10+ structural pattern matching
TruthinessWhether an expression evaluates to True in a boolean context

Summary

  • if / elif / else controls execution based on boolean conditions
  • Python uses 4-space indentation to define blocks — no curly braces
  • Combine conditions with and, or, not; chain ranges with a < x < b
  • Guard clauses (early returns) flatten nested code and improve readability
  • Ternary expressions x if cond else y are compact single-line conditionals
  • match/case (Python 3.10+) cleanly handles multiple fixed values