Chapter 5 of 21
Variables & Data Types
Current Study Module
Control Flow & Conditionals
Functions & Lambdas
Chapter 04 • Execution Logic

Control Flow, Conditionals & Pattern Matching

Control flow directs the execution path of your software. Master Python’s truthiness evaluation, the short-circuiting behavior of boolean operators, the unique for...else construct, and the powerful Structural Pattern Matching (match/case) system introduced in modern Python.

1. Truthy vs Falsy Values

In Python, any object can be evaluated directly in a boolean context without explicit comparison toTrue or False. The following values evaluate strictly to Falsy:

  • Constants: None, False
  • Zero numeric values: 0, 0.0, 0j
  • Empty sequences and collections: "" (empty string), [] (empty list), () (empty tuple), (empty dict), set()
  • Objects whose custom class implements __bool__() or __len__() returning False or 0.
# Idiomatic Pythonic Truthiness check
cart_items = []

# ANTI-PATTERN: if len(cart_items) == 0:
# PYTHONIC PATTERN:
if not cart_items:
    print("Your shopping cart is empty!")

2. Modern Structural Pattern Matching (match/case)

Introduced in Python 3.10 (PEP 634), match / case is not merely a C-style switch statement. It is a full destructuring engine that inspects the structure of lists, dicts, and objects, extracts variables, and applies conditional guards:

def handle_api_action(command: dict) -> str:
    match command:
        # Pattern 1: Exact match with literal
        case {"action": "QUIT"}:
            return "Terminating background worker..."

        # Pattern 2: Destructuring with variable capture & type matching
        case {"action": "TRANSFER", "amount": int(amt), "recipient": str(user)} if amt > 0:
            return f"Initiated wire transfer of $${amt} to ${user}."

        # Pattern 3: Sequence pattern matching
        case ["POST", str(endpoint), dict(payload)]:
            return f"Executing HTTP POST to ${endpoint} with payload keys: ${list(payload.keys())}"

        # Pattern 4: Wildcard catch-all
        case _:
            return "Error: Unknown command structure received."

print(handle_api_action({"action": "TRANSFER", "amount": 2500, "recipient": "finance_corp"}))
print(handle_api_action(["POST", "/api/v2/users", {"email": "dev@hifi.corp"}]))

3. The Unique "for...else" Loop Construct

Python features an uncommon control flow construct: the else block attached to a loop. The else block executes only if the loop finishes naturally without encountering a break statement!

# Searching for prime numbers using for...else
def check_prime(n: int) -> bool:
    if n < 2:
        return False
    for divisor in range(2, int(n ** 0.5) + 1):
        if n % divisor == 0:
            print(f"${n} is divisible by ${divisor} (Not prime)")
            break  # Exits loop early -> skips the 'else' block!
    else:
        # Executes ONLY if the loop ran to completion without hitting break!
        print(f"${n} is a PRIME number!")
        return True
    return False

check_prime(29)  # Prints: 29 is a PRIME number!

4. Assignment Expressions: The Walrus Operator (:=)

The walrus operator := (PEP 572) allows you to assign a variable and evaluate an expression in the exact same statement, avoiding redundant function calls:

# Without Walrus (Redundant length check)
# data = read_chunk()
# while len(data) > 0:
#     process(data)
#     data = read_chunk()

# With Walrus (Clean, compact stream processing)
def fetch_token_stream():
    tokens = ["token_1", "token_2", "token_3", ""]
    return iter(tokens).__next__

get_next = fetch_token_stream()
while (token := get_next()):
    print(f"Processed stream token: ${token}")

Explore Related Tools

Hand-picked utilities and calculators related to this tool.

Related Tools