Python · Module 02: Core Data Types & Control FlowTutorial 6 of 30
All Tutorials·~1.5 hrs

2.3 Control Flow: if / elif / else, Truthy/Falsy & match-case

Teach your Python programs to make smart decisions! Learn branching flowcharts, the 7 Falsy values every Python dev memorizes, clean ternary expressions, and modern match-case.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

1. Making Decisions: The Traffic-Light Analogy

Without conditionals, a program runs the exact same lines every time like a train on a single track. if / elif / else adds railway switches so your code can take different paths depending on the data.

Key rule: In an if / elif / else chain, Python checks conditions from top to bottom and executes ONLY the first branch that is True — then skips the rest!

Visual: `if / elif / else` Runs Top-to-Bottom — Only the FIRST True Branch Executes!
score = 82if score >= 90?False → skipelif score >= 80?TRUE! Run & EXITprint("Grade B")elif >= 70 / else:Never even checked!
PYTHON
score = 82

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "Need Practice"

print(f"Score {score} -> Grade {grade}")  # Score 82 -> Grade B

Beginner Trap: if + if vs. if + elif

If you accidentally write two separate if statements instead of if / elif, both can run!

  • Use elif when the choices are mutually exclusive (a student can only have one letter grade).
  • Use separate if statements when multiple independent checks should run (e.g., check if a password is long enough and check if it has a digit).

2. Truthy & Falsy Values (Writing Clean, Pythonic if Checks)

In Python, you don't have to write if len(items) > 0: or if name != "":. Every object in Python automatically counts as either Truthy or Falsy inside an if statement!

Just memorize the 7 Falsy values below — literally everything else is Truthy:

Visual: Memorize Only These 7 Falsy Values — Everything Else in Python Is Truthy!
Falsy (Act Like False in `if`)FalseNone00.0""[]{}Empty collections (`()`, `set()`) and zero numbers are Falsy.Truthy (Act Like True)True42-1"hi"[0]Even `"False"` (non-empty str) & `[0]` are Truthy!
PYTHON
cart = []

# ✗ Clunky (Java/C style)
if len(cart) == 0:
    print("Your cart is empty")

# ✓ Pythonic! Empty list [] is Falsy, so `not cart` is True
if not cart:
    print("Your cart is empty")

3. One-Line Conditional (Ternary Expression)

When you just want to pick between two simple values based on a condition, Python offers a clean 1-line conditional expression:

PYTHON
age = 20
ticket_type = "Adult" if age >= 18 else "Child"
print(ticket_type)  # Adult

Readability Rule: Only use ternary expressions for short, simple choices. Never nest a ternary inside another ternary!


4. Modern Python match-case (Python 3.10+)

If you have many exact options (like HTTP status codes or CLI commands), match-case is much cleaner than a long ladder of elifs. Use _ as the default fallback ("anything else"):

PYTHON
status_code = 404

match status_code:
    case 200 | 201:
        print("Success!")
    case 400:
        print("Bad Request")
    case 404:
        print("Page Not Found")
    case 500 | 502 | 503:
        print("Server Error — Retry")
    case _:
        print(f"Unhandled status: {status_code}")

(Unlike C/Java switch, Python match-case does not fall through — you never need break!)


5. Interactive Trace: Guard Clauses & Nested Conditionals

Pro developers avoid deeply nested if pyramids by using early checks. Step through this shipping-fee calculator:

Tracing a Shipping Fee Calculator
Interactive Line-by-Line Execution Trace · Step 1 of 6
1→order_total = 45
2is_prime = False
3if is_prime or order_total >= 50:
4 shipping = 0
5elif order_total >= 25:
6 shipping = 5
7else:
8 shipping = 10
9print(f"Total: ${order_total + shipping}")
Variables in Memory
order_total45int
Console Output
(nothing printed yet)
What just happened: Customer's cart total is $45.

Quick Quiz: Module 2.3 — Control Flow & Truthy/Falsy

Q1.Which of the following is TRUTHY in Python?
Q2.What does this code print?
x = 15
if x > 5:
    print("A")
elif x > 10:
    print("B")
Q3.In Python 3.10+ `match-case`, what does `case _:` mean?

Keep Exploring: Related Lessons & Tools

All Courses →