On this page
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`)
- > Structural Pattern Matching (`match` / `case`)
- > Loops (`for`, `while`, `break`, `continue`)
- > Loop `else` Clause
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
- tuts/programming/foundations/control_flow_and_composition
- tuts/python3/python fundamentals
- tuts/python3/tutorials
- tuts/python3/tutorials/core_fundamentals
- tuts/python3/tutorials/core_fundamentals/builtin_data_structures
- tuts/python3/tutorials/core_fundamentals/control_flow
- tuts/python3/tutorials/core_fundamentals/functions
Related notes
- tuts/python3/tutorials/core_fundamentals Linked here; links to this page; shared tags: #fundamentals, #tutorials
- tuts/python3/tutorials/core_fundamentals/builtin_data_structures Linked here; links to this page; shared tags: #fundamentals, #tutorials
- tuts/python3/tutorials/core_fundamentals/functions Linked here; links to this page; shared tags: #fundamentals, #tutorials
- tuts/python3/python fundamentals Linked here; links to this page; shared tags: #fundamentals
- tuts/python3/tutorials links to this page; shared tags: #tutorials
- tuts/programming/foundations/control_flow_and_composition links to this page
- tuts/python3/__builtins__/enumerate Linked here
- tuts/python3/__builtins__/range Linked here
- tuts/python3/__builtins__/zip Linked here
- tuts/python3/tutorials/core_fundamentals/primitive_data_types shared tags: #fundamentals, #tutorials