On this page
  1. Control Flow
  2. Contents
  3. Conditionals (if / elif / else)
  4. Structural Pattern Matching (match / case)
  5. Loops (for, while, break, continue)
  6. Loop else Clause

Control Flow

Prev: Built-in Data Structures | Up: Core Fundamentals | Next: Functions
Rel: python fundamentals, range, enumerate, zip
Ref: docs.python.org — More Control Flow Tools
Tags: #public #python3 #tutorials #fundamentals #control-flow


Contents


Conditionals (if / elif / else)

Python supports chained comparisons (0 <= x < 10), short-circuit boolean operators (and, or, not), and inline conditional expressions.

score = 87

if 90 <= score <= 100:
    grade = "A"
elif score >= 80:
    grade = "B"
else:
    grade = "C"

status = "pass" if score >= 60 else "fail"
print(grade, status)  # B pass

Structural Pattern Matching (match / case)

Introduced in Python 3.10 (PEP 634), match/case matches values by structure, binds sub-patterns to names, and supports if guards.

def handle_command(cmd: list[str]) -> str:
    match cmd:
        case ["quit" | "exit"]:
            return "Shutting down"
        case ["open", path] if path.endswith(".py"):
            return f"Opening Python file: {path}"
        case ["move", x, y]:
            return f"Moving to ({x}, {y})"
        case [action, *args]:
            return f"Action {action!r} with args {args}"
        case _:
            return "Empty command"

print(handle_command(["open", "app.py"]))
print(handle_command(["move", "10", "20"]))

Loops (for, while, break, continue)

Use for with [[__builtins__/enumerate|enumerate()]] and [[__builtins__/zip|zip()]] instead of manual index counters; use while for condition-driven loops.

names = ["Ada", "Grace", "Guido"]
years = [1815, 1906, 1956]

for idx, (name, year) in enumerate(zip(names, years, strict=True), start=1):
    print(f"{idx}. {name} ({year})")

# break exits the loop immediately; continue skips to the next iteration
for n in range(1, 10):
    if n % 2 == 0:
        continue
    if n > 5:
        break
    print(n)  # 1, 3, 5

Loop else Clause

Both for and while accept an optional else block that runs only if the loop completed normally without hitting break.

def find_first_even(numbers: list[int]) -> int | None:
    for n in numbers:
        if n % 2 == 0:
            print(f"Found even: {n}")
            return n
    else:
        print("No even number found")
        return None

find_first_even([1, 3, 5])  # Prints: No even number found

Linked from

Related notes