01A.3 Control Flow and Functions
This is the lesson where Python stops being a list of syntax facts and starts being a language you program in. Control flow decides what runs and when: if branches, for and while loops, and the match statement that routes values by shape. Functions package behaviour into named, reusable, testable units — and in Python they are far more than that: they are first-class objects you can pass around, store, return, wrap and decorate. Almost everything you will write as an AI engineer — a tool the model can call, a retry wrapper, a streaming parser, a validator — is a function plus control flow. This lesson teaches both completely, on the running support-ticket triage example, with every snippet run for real.
What you'll learn
if/elif/else, truthiness,and/or/notshort-circuiting (and the values they return), chained comparisons, the conditional expression,passand anassertpreviewmatch/casestructural pattern matching (Python 3.10+): literals, sequences, mappings, class patterns,|alternatives, guards, and when it beats anifchainforover any iterable,range,enumerate,zip,reversed,sorted;while,break/continue, the loopelse, the loop-and-a-half idiom, and the loop-and-modify trap- Functions end to end: every parameter kind (positional, keyword, default,
*args,**kwargs, keyword-only, positional-only), argument unpacking at call sites, return values, docstrings, and the mutable-default-argument trap - Scope (LEGB), closures and the late-binding gotcha, functions as first-class objects,
lambda,functools.partial - Decorators: what
@really means, writing one from scratch withfunctools.wraps, decorator arguments, a timing decorator and a retry decorator - Recursion and the recursion limit, memoisation with
functools.cache, and a preview of generators (yield) - Function design: naming, single responsibility, pure functions and side effects, idempotence,
doctest, and assert-based self-checks - The built-in function toolkit you'll use daily:
all,any,min/max/sumwithkey,sorted,map,filter,zip,isinstance,getattr
What you don't need
- Any programming experience beyond 01A.1 and 01A.2. If variables, strings and f-strings are new, do those first.
- Deep knowledge of lists, dicts and sets — this lesson uses them (a ticket is a dict) but 01A.4 teaches them properly.
- Comprehensions, iterators and generators — 01A.5 owns them; you'll see small previews here and the full treatment there.
- Classes — 01A.6 owns them. This lesson only borrows built-in "class patterns" for
match. - Exceptions and
try/except— 01A.8 owns them; this lesson only previewsraiseandassert. - An API key, a package install or a network connection. Everything here is the Python standard library and runs offline.
Setup
You need Python 3.11 or newer and a text editor. If you haven't installed Python yet, lesson 00.1 covers the machine setup and 01A.1 covers installing and running Python (uv python install 3.13, uv run script.py, or plain python3 script.py). No packages to install, no .env file, no API key — this lesson is 100% standard library.
Blocks are written to be copied and run. Save any python block as a .py file and run it with python3 file.py (or uv run file.py). Read the lesson top to bottom: within a part, blocks build on each other, so a later block may reuse a name (like tickets or words) defined a few blocks earlier. All outputs shown were produced by running the snippets on Python 3.14; the code targets 3.11+, so your output will be identical.
What you must be able to do after this lesson#
- Write if, elif and else logic and explain truthiness
- Loop over any iterable with for, enumerate and zip
- Write functions with default, keyword and variable arguments
- Avoid the mutable default argument trap
- Explain scope and closures
- Write a simple decorator with functools.wraps
- Test a function with assert and doctest
Why this matters for an AI engineer#
You will hear these phrases constantly in AI codebases, and each one is a function or a branch you now own:
| You'll hear... | You'll understand it after... |
|---|---|
| "The tool function's signature becomes the JSON schema." | 3.2 Every kind of parameter and 3.5 Docstrings |
"Wrap the call in a @retry decorator." |
5.3 Decorators with arguments and 5.4 A timing decorator |
"Route on the finish_reason, don't parse blindly." |
1.6 match/case |
| "Don't use a mutable default argument." | 3.3 The mutable-default trap |
"Cache it with functools.cache / lru_cache." |
4.5 Memoisation |
| "That closure captures the loop variable — classic late binding." | 4.2 Closures and the late-binding gotcha |
"Stream it: for chunk in stream:" |
4.6 Generators: a preview |
"Validate with isinstance before you trust the shape." |
7.3 len, isinstance, getattr |
| "Keep the handler pure; do I/O at the edges." | 6.2 Pure functions and side effects |
| "The approver is just a callback." | 4.3 Functions as values |
Part 1: Making decisions — conditionals#
1.1 if, elif and else#
The most basic program shape: do this if a condition holds, otherwise do that. Python's version is deliberately spare — no parentheses required, no braces, and the block is marked by indentation (which 01A.1 introduced):
score = 72
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(grade)CThree rules to internalise on day one:
- Conditions are expressions. Anything that produces a value can sit after
if— the value is tested for truthiness (1.2), not necessarilyTrue/False. elifmeans "else, if". Only the first true branch runs. If none match,elseruns.- Indentation is the block. Everything indented under the
ifbelongs to it. Un-indent and you're out. This is why Python rejects tab/space mixes that make the structure ambiguous — the block boundary must be unambiguous.
1.2 Truthiness in conditions#
01A.1 gave you the truthiness table; here is why it matters. if doesn't require a boolean — it asks "is this value truthy?" and the falsy set is small and fixed:
| Falsy | Everything else |
|---|---|
False, None |
True |
0, 0.0, 0j |
every non-zero number |
"" (empty string) |
every non-empty string, including "0" and "False" |
[], {}, (), set(), b"", bytearray() (any empty container) |
every non-empty container |
Two consequences that bite in production:
if user_input:silently treats"0"as true (it's a non-empty string) and0as false. If a user types0meaning "zero items",if count:skips the branch.if response:on an API result that's an empty list[]takes the "no data" path — correct — butif response is not None:is what you want when an empty result is still a valid answer. 01A.4 and 01A.9 lean on this distinction constantly.
1.3 and, or, not: the values they return#
Python's boolean operators are the subtlest thing in this part, because and and or don't return booleans — they return one of their operands:
name = ""
display = name or "anonymous" # "" is falsy -> "anonymous"
print(display)
count = 0
label = count or "no items" # 0 is falsy -> "no items" (the classic trap)
print(label)
settings = {"theme": "dark", "accent": "sepia"}
theme = settings.get("theme") and settings.get("accent", "blue") # left truthy -> returns the RIGHT operand
print(theme)anonymous
no items
sepiaThe rule, precisely:
a or breturnsaifais truthy, elseb. ("Give mea, or fall back tob.")a and breturnsaifais falsy, elseb. ("Checkafirst; only if it passes, look atb.")not aalways returns a real boolean — the one operator that doesn't pass values through.
This gives you two idioms you'll see everywhere:
user = {"name": "", "role": "admin", "active": True}
display_name = user.get("name") or "anonymous" # fallback for empty/None
is_admin = user.get("role") == "admin" and user.get("active") # both must hold
print(display_name, is_admin)anonymous TrueShort-circuiting means the right operand doesn't even run when the left one decides the result — which matters when the right side is expensive or has side effects:
calls = []
def side_effect(x):
calls.append(x)
return x
result = False and side_effect("never ran")
print(result, calls) # False []
result = True or side_effect("never ran either")
print(result, calls) # True []
result = True and side_effect("ran once")
print(result, calls) # ran once ['ran once']False []
True []
ran once ['ran once']False and ... stops at False; True or ... stops at True; only True and ... evaluates the right side. This is why if user and user.is_admin: never crashes on user = None — the second check never runs. Guard clauses written this way are the Pythonic alternative to nested ifs.
1.4 Chained comparisons#
Python lets you write a < b < c, which means a < b and b < c — with a subtlety: the middle operand is evaluated once, not twice:
ticks = []
def tick(x):
ticks.append(x)
return x
print(tick(1) < tick(2) < tick(3))
print("ticks:", ticks)
ticks.clear()
print(tick(1) < tick(2) and tick(2) < tick(3))
print("ticks:", ticks)
score = 72
print(0 <= score < 100) # the range check you write daily
print(1 < 2 < 3 < 4)True
ticks: [1, 2, 3]
True
ticks: [1, 2, 2, 3]
True
TrueIn the chained version tick(2) ran once; written out with and it ran twice. For pure values the difference is invisible; for a function call it's a real (if small) saving — and it's the semantics the language guarantees. 0 <= score < 100 is how every Python programmer writes "between 0 and 100"; the C-style score >= 0 && score < 100 doesn't exist here.
1.5 The conditional expression#
Python has an expression form of if — x if condition else y — for choosing a value, not running a block:
open_tickets = 3
msg = f"{open_tickets} open ticket{'s' if open_tickets != 1 else ''}"
print(msg)3 open ticketsRead it as "msg is the f-string if open_tickets != 1, else the plural-less version" — the condition sits in the middle, which trips up everyone at first. Use it for short choices ("yes" if ok else "no", name or "anonymous" is often clearer); once it nests or wraps a line, switch back to a real if statement. A conditional expression is an expression: it produces a value and can sit inside a call or assignment. An if statement runs blocks and produces nothing.
1.6 match/case: structural pattern matching#
Added in Python 3.10 (PEP 634), match is often called "switch on steroids" — but that's underselling it. An if chain tests conditions; match tests shape: "is this value a dict with status: "closed"?", "is this a two-element list whose first item is "restart"?", "is this an int below zero?". It reads top to bottom like if/elif, first match wins, and case _ is the wildcard else.
def route_queue(item):
"""Route a small dict-shaped request to a queue name."""
match item:
case {"status": "closed"}:
return "archive"
case {"priority": "urgent", "queue": q}:
return f"oncall:{q}"
case {"kind": "billing"} | {"kind": "refund"}:
return "finance"
case {"kind": kind} if kind in ("outage", "security"):
return "sre"
case _:
return "triage"The pattern vocabulary, one example each:
| Pattern | Matches | Example |
|---|---|---|
| Literal | an exact value | case "closed":, case 404: |
| Capture | anything, binds a name | case q: |
| Wildcard | anything, binds nothing | case _: |
| Value (dotted name) | a named constant | case Color.RED: |
| Sequence | a list/tuple of a given shape | case ["restart", service]: |
| Mapping | a dict containing these keys | case {"status": "closed"}: |
| Class | an instance of a type | case int(n):, case str(s): |
OR | |
any of several patterns | case "billing" | "refund": |
Guard if |
an extra condition on the match | case x if x > 0: |
Star * |
"the rest" of a sequence | case ["help", *topics]: |
Mapping rest ** |
the other keys of a dict | case {"kind": "note", **rest}: |
as binding |
name the whole matched value (often with |) |
case ("GET" | "POST") as method: |
Running it:
tests = [
{"status": "closed", "kind": "billing"},
{"status": "open", "priority": "urgent", "queue": "payments"},
{"status": "open", "kind": "refund"},
{"status": "open", "kind": "outage"},
{"status": "open", "kind": "feature-request"},
]
for t in tests:
print(route_queue(t), "<-", t)archive <- {'status': 'closed', 'kind': 'billing'}
oncall:payments <- {'status': 'open', 'priority': 'urgent', 'queue': 'payments'}
finance <- {'status': 'open', 'kind': 'refund'}
sre <- {'status': 'open', 'kind': 'outage'}
triage <- {'status': 'open', 'kind': 'feature-request'}Note the first result: a closed billing ticket archives, because {"status": "closed"} is checked first — order matters exactly as in if/elif. The mapping pattern {"priority": "urgent", "queue": q} matches a dict that has at least those keys (extra keys are fine) and binds q to the value of "queue". The {"kind": kind} if kind in (...) case shows a guard: the pattern binds kind, then the if decides whether the case really matches.
Sequences and guards together make match shine for parsing-shaped input:
def handle(command):
match command.split():
case ["status"]:
return "ok"
case ["restart", service]:
return f"restarting {service}"
case ["help", *topics]:
return f"help: {', '.join(topics) if topics else 'everything'}"
case _:
return "unknown command"
for cmd in ["status", "restart api", "help tickets billing", "help", "dance"]:
print(f"{cmd!r:28} -> {handle(cmd)}")'status' -> ok
'restart api' -> restarting api
'help tickets billing' -> help: tickets, billing
'help' -> help: everything
'dance' -> unknown command["help", *topics] is a sequence pattern with a star: first element must be "help", and *topics captures the remaining words as a list (empty if there are none). command.split() returns a list of words, so handle("help tickets billing") sees ["help", "tickets", "billing"] — a shape, matched directly.
Class patterns let you test type plus capture in one step — no class definition needed, because built-in types are classes too:
def describe(value):
match value:
case None:
return "nothing"
case True:
return "yes"
case int(n) if n < 0:
return f"negative int {n}"
case int(n):
return f"non-negative int {n}"
case str(s) if len(s) > 10:
return "long string"
case str(s):
return f"short string {s!r}"
case _:
return "something else"
for v in [None, True, -5, 42, "hello world!", "hi", 3.14]:
print(f"{v!r:15} -> {describe(v)}")None -> nothing
True -> yes
-5 -> negative int -5
42 -> non-negative int 42
'hello world!' -> long string
'hi' -> short string 'hi'
3.14 -> something elseTwo traps worth knowing:
True/False/Noneare literal patterns, but the singletons compare by identity, not==—case True:will not catch1or1.0. Numeric and string literals do use==, socase 1:would also matchTrue(becauseTrue == 1) if it came first — keepcase True:/case False:ahead of any numeric cases when both can appear, as above.- A bare name is a capture, not a comparison.
case status:binds the namestatusto anything — it does not checkvalue == status. To compare against a variable you must use a value pattern (a dotted name likeconfig.DEFAULT) or a guard:case s if s == status:.
When match beats an if chain: when you're dispatching on the shape of one value (a parsed JSON object, a command's words, an event type), when several cases share structure, or when a reviewer should see the cases as a table of shapes rather than a pile of conditions. When you're testing unrelated conditions on different variables, plain if is clearer. Part 8 uses match for the ticket router; 01A.11 maps it to switch for switchers.
1.7 pass and assert (a preview)#
pass is a no-op statement — it does nothing, but it satisfies the grammar where a block is required:
def stub():
pass # a body that does nothing yet
print(stub()) # NoneNoneYou'll use it for "not implemented yet" stubs, for except blocks that deliberately ignore an error (see 01A.8), and occasionally as a placeholder in match. It is not a comment — the function still returns None, exactly like a function with no return.
assert checks an assumption and raises AssertionError if it's false:
x = 10
assert x > 0, "x must be positive"
print("assert passed")assert passedPart 2: Doing things repeatedly — loops#
2.1 for loops over iterables#
Python's for is a for-each: it doesn't count, it iterates — it asks an iterable for its items one at a time. Lists, strings, dicts, ranges and (later) files and streams all work:
tickets = [
{"id": "T-1001", "subject": "Cannot log in", "points": 3},
{"id": "T-1002", "subject": "Invoice wrong", "points": 2},
{"id": "T-1003", "subject": "API 500s", "points": 5},
]
for t in tickets:
print(f'{t["id"]}: {t["subject"]}')T-1001: Cannot log in
T-1002: Invoice wrong
T-1003: API 500sThe loop variable t is rebound each iteration — last one wins when the loop ends. You can loop over a string (for ch in "abc"), a tuple, a range, and anything else that yields items (01A.5 explains the machinery). Iterating a dict yields its keys; for k, v in d.items() unpacks each key/value pair — 01A.4 owns dicts properly.
2.2 range, enumerate, zip, reversed, sorted#
Five helpers cover almost every loop you'll write:
for i, t in enumerate(tickets, start=1):
print(f"{i}. {t['id']}")
ids = ["T-1001", "T-1002", "T-1003"]
subjects = ["Cannot log in", "Invoice wrong", "API 500s"]
for tid, subj in zip(ids, subjects):
print(tid, "=", subj)
for n in range(3):
print("range(3):", n)
print("range(1, 6, 2):", list(range(1, 6, 2)))
for t in reversed(tickets):
print("reversed:", t["id"])
words = ["Zebra", "apple", "Mango"]
print("sorted plain:", sorted(words))
print("sorted key=str.lower:", sorted(words, key=str.lower))1. T-1001
2. T-1002
3. T-1003
T-1001 = Cannot log in
T-1002 = Invoice wrong
T-1003 = API 500s
range(3): 0
range(3): 1
range(3): 2
range(1, 6, 2): [1, 3, 5]
reversed: T-1003
reversed: T-1002
reversed: T-1001
sorted plain: ['Mango', 'Zebra', 'apple']
sorted key=str.lower: ['apple', 'Mango', 'Zebra']What each one is for:
| Helper | Gives you | The trap |
|---|---|---|
range(stop) / range(start, stop, step) |
integers start..stop-1 — stop is excluded |
range(1, 6, 2) → 1, 3, 5 (not 6) |
enumerate(iterable, start=1) |
(index, item) pairs |
default start=0; pass start=1 for humans |
zip(a, b, ...) |
tuples pairing items positionally | stops at the shortest — silently drops the tail |
reversed(seq) |
items in reverse order | needs a sequence (has len), not any iterable |
sorted(iterable, key=..., reverse=...) |
a new sorted list | doesn't touch the original; list.sort() sorts in place and returns None |
The accumulator pattern — carry a running total through a loop — is the most common loop shape in data code:
total = 0
for t in tickets:
total += t["points"]
print("total points:", total)total points: 102.3 while loops and the loop-and-a-half#
while repeats while a condition holds — use it when you don't know how many iterations you need up front:
attempts = 0
while attempts < 3:
attempts += 1
print(f"attempt {attempts}")attempt 1
attempt 2
attempt 3The loop-and-a-half is the idiom for "do something, then decide whether to continue" — read until you hit a sentinel, retry until success:
lines = iter(["first", "second", None, "never reached"])
seen = []
while True:
line = next(lines, None)
if line is None:
break
seen.append(line)
print("seen:", seen)seen: ['first', 'second']while True: plus a break reads better than contorting a while condition to check "haven't hit the end yet". (next(iterator, default) is how you pull one item safely — 01A.5 owns iterators; here it stands in for "read a line until EOF".)
2.4 break, continue and the loop else#
Two control statements inside a loop:
break— leave the loop immediately.continue— skip to the next iteration.
And the strange one: else on a loop runs when the loop finishes without hitting break:
for n in range(6):
if n == 4:
break
if n == 1:
continue
print("no-break loop saw", n)
else:
print("loop finished WITHOUT break")
print("---")
for n in range(6):
if n == 4:
break
else:
print("this else never prints: break ran")
k = 0
while k < 5:
k += 1
if k == 3:
continue
else:
print("while-else ran: k =", k)no-break loop saw 0
no-break loop saw 2
no-break loop saw 3
---
while-else ran: k = 5Read it carefully: the first loop printed 0, 2, 3 (1 was continued, 4 hit break), and its else did not run. The second loop's else also didn't run — break skips it. The while loop ran to completion (no break), so its else printed k = 5. The else is for "the loop exhausted without finding what it wanted" — for...else is Python's version of a flag variable, and it's why Exercise 5 can write find_index without a found flag.
2.5 Nested loops and the loop-and-modify trap#
Nested loops are just loops inside loops — outer iteration, inner iteration:
pairs = []
for a in ("GET", "POST"):
for b in ("/tickets", "/users"):
pairs.append(f"{a} {b}")
print(pairs)['GET /tickets', 'GET /users', 'POST /tickets', 'POST /users']Watch the order: the inner loop completes fully for each outer step — that's why POST /users comes last, not interleaved.
The loop-and-modify trap is the classic real-world bug: changing a list while iterating it. Removing items shifts everything left, so the iterator skips the element that slid into the removed one's place:
items = [1, 2, 3, 4, 5]
for x in items:
if x > 2:
items.remove(x)
print("buggy remove-while-iterating:", items)
items = [1, 2, 3, 4, 5]
kept = []
for x in items:
if x <= 2:
kept.append(x)
print("safe filter:", kept)buggy remove-while-iterating: [1, 2, 4]
safe filter: [1, 2]The buggy version left 4 in the list even though 4 > 2 — it was skipped when 3 was removed and everything shifted. The fix is almost always build a new list rather than edit in place; 01A.5 shows the idiomatic one-liner. The same trap applies to del items[i] inside for i in range(len(items)) — deleting shifts indices too.
2.6 Iteration vs recursion#
Every loop you've written is iteration: repeat a step until done. Recursion is the alternative — a function that calls itself:
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print("5! =", factorial(5))5! = 120factorial(5) calls factorial(4), which calls factorial(3)... down to factorial(1), then the results multiply back up on the way out. Recursion is elegant for problems that are defined recursively (tree walks, divide-and-conquer, parsing nested structures) but it has a hard ceiling: Python caps the call depth at 1000 by default.
import sys
print("recursion limit:", sys.getrecursionlimit())
def forever(n):
return forever(n + 1)
try:
forever(0)
except RecursionError as e:
print("RecursionError:", str(e)[:70])recursion limit: 1000
RecursionError: maximum recursion depth exceededRecursionError is a RuntimeError subclass — you'll meet it properly in 01A.8. The practical rule: prefer loops for anything that could run deep (a list of a million items recurses to death instantly; a loop doesn't care). Reserve recursion for genuinely recursive data or problems, keep the depth bounded, and never raise sys.setrecursionlimit to "fix" it — that trades a clean error for a stack overflow crash.
Part 3: Writing functions#
3.1 def, arguments and return values#
A function packages a named block of code into something you can call with different inputs:
def greet(name):
return f"Hello, {name}!"
print(greet("Ada"))
print(greet("Grace"))Hello, Ada!
Hello, Grace!def name(parameters): defines it; name(arguments) calls it. Parameters are the names in the def; arguments are the values you pass at the call. The return statement hands a value back and ends the function immediately — anything after return in the same block never runs.
A function with no return returns None — silently. This is the single most common beginner bug:
def broken_add(a, b):
a + b # computed, then thrown away
print("broken_add returns:", broken_add(2, 3))
def good_add(a, b):
return a + b
print("good_add returns:", good_add(2, 3))broken_add returns: None
good_add returns: 5And returning vs printing are different jobs. print writes to the screen for a human; return hands a value back to the caller's code:
def print_sum(a, b):
print(a + b)
result = print_sum(2, 3)
print("captured:", result)5
captured: Noneprint_sum showed you 5 but gave the caller None — the sum was displayed, not returned. Library and tool code almost always returns; print belongs in your command-line entry point (main()), not inside helpers. 6.2 makes this a design rule.
3.2 Every kind of parameter#
Python gives you precise control over how arguments may be passed — learn the kinds once and every signature in the stdlib and the LLM SDKs reads clearly:
def find_tickets(tickets, status=None, limit=10, *, archived=False, **filters):
"""Return up to `limit` tickets matching the filters."""
matched = []
for t in tickets:
if status is not None and t["status"] != status:
continue
if not archived and t.get("archived"):
continue
# **filters soaks up extra name=value pairs; every one must match
fits = True
for key, value in filters.items():
if t.get(key) != value:
fits = False
break
if not fits:
continue
matched.append(t)
if len(matched) >= limit:
break
return matched
# the ticket data every call below runs on
tickets = [
{"id": "T-1", "status": "open", "region": "eu"},
{"id": "T-2", "status": "closed", "region": "us"},
{"id": "T-3", "status": "open", "region": "eu"},
{"id": "T-4", "status": "open", "region": "eu", "archived": True},
]| Kind | Syntax | How it's passed | Example |
|---|---|---|---|
| Positional-or-keyword | tickets, status, limit |
by position in order, or by name | find_tickets(ts) / find_tickets(ts, status="open") |
| Default | status=None |
optional — the default applies when the argument is omitted | find_tickets(ts) |
| Keyword-only | *, archived=False |
must be named | find_tickets(ts, archived=True) |
| Variadic keyword | **filters |
collects extra name=value pairs into a dict |
find_tickets(ts, region="eu") |
| Variadic positional | *args |
collects extra positional values into a tuple | ticket_ids(t1, t2, t3) |
| Positional-only | def f(a, /) |
cannot be passed by name | repeat("ab", 3) |
Two details in that signature are worth a second look. The bare * — a star with no name — is a separator: everything after it must be passed by keyword, which is how archived is protected from positional mix-ups (the TypeError below proves it). And **filters soaks up any other keyword arguments into a dict, the same trick APIs use to accept "these options, plus whatever else you invent later".
print([t["id"] for t in find_tickets(tickets)]) # defaults
print([t["id"] for t in find_tickets(tickets, limit=2)]) # keyword arg
print([t["id"] for t in find_tickets(tickets, "open")]) # positional status
print([t["id"] for t in find_tickets(tickets, archived=True)]) # keyword-only
print([t["id"] for t in find_tickets(tickets, region="eu")]) # **filters must all match
try:
find_tickets(tickets, None, 10, True) # archived passed positionally -> TypeError
except TypeError as e:
print("TypeError:", e)
def repeat(text, times, /):
return text * times
print(repeat("ab", 3))
try:
repeat(text="ab", times=2) # positional-only names can't be keywords
except TypeError as e:
print("TypeError:", e)['T-1', 'T-2', 'T-3']
['T-1', 'T-2']
['T-1', 'T-3']
['T-1', 'T-2', 'T-3', 'T-4']
['T-1', 'T-3']
TypeError: find_tickets() takes from 1 to 3 positional arguments but 4 were given
ababab
TypeError: repeat() got some positional-only arguments passed as keyword arguments: 'text, times'The last find_tickets call shows **filters at work: region="eu" isn't a named parameter, so it lands in filters, and the ticket must match every pair — T-2 is us and T-4 is archived, leaving T-1 and T-3.
*args gathers extra positional arguments into a tuple — and the mirror image, * and ** at the call site, unpack a sequence or dict into arguments:
def ticket_ids(*args):
"""Variadic: `args` is a tuple of whatever was passed."""
return [t["id"] for t in args]
print(ticket_ids(tickets[0], tickets[1]))
print(ticket_ids(*tickets)) # * unpacks the list into args
query = {"status": "open", "limit": 2}
print([t["id"] for t in find_tickets(tickets, **query)]) # ** unpacks a dict['T-1', 'T-2']
['T-1', 'T-2', 'T-3', 'T-4']
['T-1', 'T-3']def f(*args) and calling f(*items) are the same syntax pointing in opposite directions: in the signature it gathers, at the call site it spreads. f(**d) does the same for keywords — {"status": "open"} becomes status="open". You'll use call-site unpacking constantly: print(*rows), func(**config), zip(*pairs).
3.3 The mutable-default-argument trap#
The most famous Python gotcha, and it earns its fame — it produces a bug that looks impossible until you understand it:
def add_tag(tag, tags=[]):
tags.append(tag)
return tags
print(add_tag("urgent")) # ['urgent']
print(add_tag("billing")) # ['urgent', 'billing'] <- surprise!
print(add_tag("vip")) # all three!['urgent']
['urgent', 'billing']
['urgent', 'billing', 'vip']tags=[] looks like "a fresh empty list each call". It isn't. Default values are evaluated once, when the def executes — the same list object is reused for every call that doesn't pass tags. First call appends to it; second call sees the leftovers.
The fix is the None sentinel — "no argument given" becomes None, and you build the real default inside:
def add_tag_fixed(tag, tags=None):
if tags is None:
tags = []
tags.append(tag)
return tags
print(add_tag_fixed("urgent"))
print(add_tag_fixed("billing"))
print(add_tag_fixed("vip", ["x"])) # caller's list still works['urgent']
['billing']
['x', 'vip']The rule: never use a mutable default ([], {}, set()). Immutable defaults (None, numbers, strings, tuples) are fine because they can't accumulate state. This bug bites hardest in long-running processes — a web server's function with cache={} silently grows forever — which is why reviewers flag it on sight. If you genuinely need a shared default, make it a module-level constant and say so in the docstring.
3.4 Returning several values, and returning vs printing#
return can hand back multiple values as a tuple, and the caller unpacks them:
def minmax(xs):
return min(xs), max(xs) # a tuple, packed
lo, hi = minmax([3, 1, 4, 1, 5]) # unpacked at the call site
print(lo, hi)1 5It's really one value — a tuple (1, 5) — that Python unpacks for you on both sides. You can also return a dict or a dataclass (01A.6) when the pieces have names; tuples are fine for two or three related values ((lo, hi), (total, average)).
Early returns keep functions flat: handle the edge cases first and return, leaving the main path unindented at the bottom:
def label_for(score):
if score is None:
return "unknown"
if score >= 90:
return "excellent"
if score >= 70:
return "ok"
return "needs work"This beats nesting every branch — the "guard clause" style that 01A.10 codifies.
3.5 Docstrings and help()#
A docstring is the string literal right after def — it documents the function for humans and for help():
def classify_ticket(text):
"""Classify a ticket's text into a routing label.
Rules are checked in order; the first match wins.
Args:
text: The ticket subject and body, as one string.
Returns:
One of "auth", "billing", "infra" or "general".
Examples:
>>> classify_ticket("Cannot log in after reset")
'auth'
>>> classify_ticket("Invoice total looks wrong")
'billing'
"""
t = text.lower()
if "log in" in t or "login" in t or "password" in t:
return "auth"
if "invoice" in t or "charged" in t or "billing" in t:
return "billing"
if "500" in t or "error" in t or "down" in t:
return "infra"
return "general"Three common styles — Google (Args:/Returns: blocks, above), NumPy (Parameters/Returns with underline dashes), and reST (:param x: fields). The path uses Google style; the exact convention matters less than having one. help() renders any of them:
Help on function classify_ticket in module __main__:
classify_ticket(text)
Classify a ticket's text into a routing label.
Rules are checked in order; the first match wins.
Args:
text: The ticket subject and body, as one string.
Returns:
One of "auth", "billing", "infra" or "general".
Examples:
>>> classify_ticket("Cannot log in after reset")
'auth'
>>> classify_ticket("Invoice total looks wrong")
'billing'A type-hint preview: you can annotate parameters and the return without changing behaviour:
def classify_ticket(text: str) -> str:
...text: str says "expects a string", -> str says "returns a string". Hints are documentation that tools can check — they don't enforce anything at run time (pass an int and it still runs until something breaks). 01A.10 teaches them properly; for now, annotate simple cases and let later lessons deepen it.
Part 4: Scope, closures and first-class functions#
4.1 Scope: LEGB#
When a function uses a name, Python looks it up in a fixed order — LEGB: Local (the function's own variables), Enclosing (the function it was defined inside), Global (the module level), Builtins (len, print, str...). First match wins:
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print("inner sees:", x)
inner()
print("outer sees:", x)
outer()
print("module sees:", x)
def read_x():
return x # no local x -> falls through to global
print("read_x sees:", read_x())inner sees: local
outer sees: enclosing
module sees: global
read_x sees: globalinner's x = "local" shadows everything above it; outer's x shadows the module's; read_x finds no local or enclosing x, so it reads the global. Assignment creates a local unless you say otherwise — that's the rule behind both global and nonlocal.
4.2 Closures and the late-binding gotcha#
A closure is a function that remembers the variables of the scope it was created in — even after that scope has returned:
def make_multiplier(n):
def multiply(x):
return x * n # n comes from the enclosing scope
return multiply
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5), triple(5), double(10))10 15 20make_multiplier(2) returns multiply with n "remembered" as 2; make_multiplier(3) makes a separate multiply remembering 3. Each call to the outer function creates a fresh enclosing scope — that's why double and triple don't interfere. Closures are how Python builds stateful functions without classes, and they're everywhere: decorators (Part 5), callbacks, and the functools.partial-style factories in SDKs.
The late-binding gotcha is the flip side — closures capture variables, not values:
funcs = [lambda: i for i in range(3)]
print("late binding:", [f() for f in funcs])
funcs = [lambda i=i: i for i in range(3)]
print("early binding:", [f() for f in funcs])late binding: [2, 2, 2]
early binding: [0, 1, 2]All three lambdas share the same i — by the time you call them, the loop finished and i is 2. The fix lambda i=i: i binds i's current value as a default argument at creation time. This bites in any loop that creates functions (handlers, callbacks, deferred calls) — Exercise 8 has you fix it.
nonlocal and global are the escape hatches for assigning to an outer name:
def make_counter():
count = 0
def increment():
nonlocal count # assign in the enclosing function's scope
count += 1
return count
return increment
counter = make_counter()
print(counter(), counter(), counter())
calls_made = 0
def note_call():
global calls_made # assign in the module scope
calls_made += 1
note_call(); note_call()
print("calls_made:", calls_made)1 2 3
calls_made: 2nonlocal count lets increment do count += 1 on the enclosing function's variable — that's how the counter "remembers" between calls (a closure with state). global reaches the module level. Use them sparingly: nonlocal for genuine shared state in a factory, global almost never — module-level mutable state makes code hard to test and reason about (6.2).
4.3 Functions as values: lambda and partial#
Functions are first-class objects: you can assign them, pass them, return them, store them in lists — just like any other value:
def greet(name):
return f"Hello, {name}!"
f = greet # store a function in a variable
print(f("Ada"))
def apply_twice(fn, value):
return fn(fn(value))
def shout(s):
return s.upper() + "!"
print(apply_twice(shout, "hi"))Hello, Ada!
HI!!apply_twice takes a function as an argument — higher-order functions are the whole basis of callbacks, decorators and map/filter/sorted(key=...). A lambda is a tiny anonymous function for one-off use:
def make_adder(n):
return lambda x: x + n
add5 = make_adder(5)
print(add5(10))15lambda x: x + n is def's shorthand — one expression, no name, no statements. It's perfect for key= arguments and tiny callbacks, but if it needs logic or a docstring, write a real def — readability wins. functools.partial freezes some arguments of a function to make a specialized version:
from functools import partial
def power(base, exp):
return base ** exp
square = partial(power, exp=2) # bind exp=2; base stays free
cube = partial(power, exp=3)
print(square(5), cube(2))25 8partial is def without the boilerplate — handy when you want "power with exp=2 baked in" but square still needs base. You'll see it in SDKs that pre-bind a client or a model.
4.4 Recursion (contd.) and the limit#
2.6 introduced recursion and the 1000-deep limit. Two more things worth knowing:
- Every recursive call costs memory — a new frame on the call stack.
sys.getrecursionlimit()returns 1000 by default; deep recursion raisesRecursionErrorbefore it can overflow the C stack. - Memoisation (4.5) turns exponential recursion into linear time by caching results —
fib(30)without it makes ~2.7 million calls, with it just 31 (one per distinctn), andfib(45)without it would make ~3.7 billion: the difference between a blink and a hang.
The practical rule stands: loops for iteration, recursion for recursive problems, and never recurse deeper than you must.
4.5 Memoisation with functools.cache#
Memoisation caches a function's results so repeated calls with the same arguments don't recompute:
from functools import cache
seen = []
@cache
def fib(n):
seen.append(n)
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print("fib(10) =", fib(10))
print("distinct args computed:", sorted(set(seen)), "total calls:", len(seen))
seen.clear()
print("fib(10) again =", fib(10), "| new computations:", len(seen))fib(10) = 55
distinct args computed: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] total calls: 11
fib(10) again = 55 | new computations: 0Without @cache, fib(10) makes 177 calls; with it, 11 — each n computed once, then served from the cache. The second fib(10) does zero new work. functools.cache (3.9+) is lru_cache(maxsize=None) — unbounded; lru_cache(maxsize=128) bounds memory for huge input spaces.
4.6 Generators: a preview of yield#
A function containing yield is a generator — calling it returns an object you loop over, and each yield hands one value to the loop and pauses until asked for the next:
def countdown(n):
while n > 0:
yield n
n -= 1
for x in countdown(3):
print("countdown:", x)
g = countdown(2)
print("next:", next(g))
print("next:", next(g))countdown: 3
countdown: 2
countdown: 1
next: 2
next: 1The function doesn't run when you call countdown(3) — it runs as you iterate, producing values lazily one at a time. That's why generators are perfect for streams, large files and infinite sequences: they use memory for one item, not all of them. 01A.5 owns them properly — yield from, send/close, itertools, and the streaming pipelines that 03.3 builds on.
Part 5: Decorators#
Deep-dive
5.1 What @ really does#
You've seen @retry, @cache, @dataclass — a decorator is a function that takes a function and returns a function. The @ syntax is just assignment sugar:
def announce(fn):
def wrapper(*args, **kwargs):
print(f"--> calling {fn.__name__}")
result = fn(*args, **kwargs)
print(f"<-- returned {result!r}")
return result
return wrapper
@announce
def greet(name, punctuation="!"):
"""Greet someone."""
return f"Hello, {name}{punctuation}"is exactly equivalent to:
def greet(name, punctuation="!"):
"""Greet someone."""
return f"Hello, {name}{punctuation}"
greet = announce(greet)announce(greet) returns wrapper, and greet is rebound to it. Every call to greet(...) now runs wrapper, which logs and then calls the original fn. The original function is captured in the closure — that's the whole trick.
5.2 Writing a decorator from scratch#
The pattern is always the same shape: an outer function that receives fn, an inner wrapper that does the extra work around fn(*args, **kwargs), and return wrapper:
import functools
def announce(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
print(f"--> calling {fn.__name__} with {args} {kwargs}")
result = fn(*args, **kwargs)
print(f"<-- {fn.__name__} returned {result!r}")
return result
return wrapper
@announce
def greet(name, punctuation="!"):
"""Greet someone."""
return f"Hello, {name}{punctuation}"
print(greet("Ada"))
print("name preserved:", greet.__name__)
print("doc preserved:", greet.__doc__)--> calling greet with ('Ada',) {}
<-- greet returned 'Hello, Ada!'
Hello, Ada!
name preserved: greet
doc preserved: Greet someone.wrapper(*args, **kwargs) forwards any signature — positional, keyword, defaults — to the wrapped function, so the decorator works on functions it knows nothing about. functools.wraps(fn) copies __name__, __doc__ and friends onto the wrapper; without it the decorated function looks like wrapper to help(), tracebacks and introspection tools:
def no_wraps(fn):
def wrapper(*args, **kwargs):
return fn(*args, **kwargs)
return wrapper
@no_wraps
def secret():
"""You can't see me."""
return 42
print("without wraps:", secret.__name__, "|", secret.__doc__)without wraps: wrapper | Nonesecret.__name__ is "wrapper" and its docstring is gone — help(secret) and traceback would all say wrapper, making debugging miserable. Always use @functools.wraps. The undecorated equivalent greet = announce(greet) works identically — @ is just cleaner.
5.3 Decorators with arguments#
@retry(times=3) has parentheses — so retry isn't the decorator, it's a function that returns one. Three levels: outer takes the decorator's args, middle takes fn, inner is the wrapper:
import functools
def retry(times=3, errors=(Exception,)):
def decorator(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
for attempt in range(1, times + 1):
try:
return fn(*args, **kwargs)
except errors:
if attempt == times:
raise
print(f" attempt {attempt} failed; retrying")
return wrapper
return decorator
calls = {"n": 0}
@retry(times=3)
def flaky():
calls["n"] += 1
if calls["n"] < 3:
raise ValueError("temporary failure")
return "success"
print("flaky():", flaky())
print("total attempts:", calls["n"]) attempt 1 failed; retrying
attempt 2 failed; retrying
flaky(): success
total attempts: 3@retry(times=3) calls retry(times=3) → returns decorator → decorator(flaky) → returns wrapper → flaky is rebound to wrapper. The wrapper tries fn up to times times, re-raising on the last failure. This is a toy retry — production retries need backoff, jitter, Retry-After and per-error-type decisions, which is exactly 01B.9 and 03.8 Part 8 (the tenacity library) own.
5.4 A timing decorator#
The canonical "measure how long" decorator — here the elapsed time varies by machine, so the output is labelled illustrative:
import functools
import time
def timed(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = fn(*args, **kwargs)
elapsed = time.perf_counter() - start
print(f"{fn.__name__} took {elapsed * 1000:.1f} ms")
return result
return wrapper
@timed
def slow_sum(n):
total = 0
for i in range(n):
total += i * i
return total
print("sum of squares:", slow_sum(2_000_000))slow_sum took 44.4 ms
sum of squares: 2666664666667000000The decorators stack — bottom-up application, top-down execution:
def loud(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
return fn(*args, **kwargs).upper()
return wrapper
@loud
@retry(times=2)
def whisper():
return "hello"
print("stacked:", whisper())stacked: HELLO@loud wraps @retry's wrapper wraps whisper — call order is loud → retry → whisper, return order reverses. Decorators compose like function calls.
5.5 Where decorators appear in the AI path#
Decorators are how Python libraries add behaviour without changing your code:
| Decorator you will meet | What it does | Where |
|---|---|---|
@cache / @lru_cache |
memoise results | 4.5, 11B.3 |
@retry (tenacity) |
retry with backoff | 01B.9, 03.8 |
@beta_tool |
build a tool schema from type hints + docstring | 08A.2 §5.1 |
@workflow / @task |
trace stages in observability | 11A.1 §3.4 |
Modal @app.function |
turn a Python function into a GPU endpoint | 11C.6 §6.2 |
@dataclass |
generate __init__/__repr__/__eq__ |
01A.6 |
@property, @classmethod, @staticmethod |
method variants | 01A.6 |
Every one is the same trick you just wrote by hand: take a function, wrap it, return the wrapper. Understanding @ demystifies half the "magic" decorators in the ecosystem.
Part 6: Designing functions and testing them#
6.1 Design rules that scale#
Functions are where code quality is won or lost. The rules that matter:
- Name it like a verb phrase —
classify_ticket,route,priority— notprocessordo_stuff. The name should tell you what it returns. - One job per function. If you need "and" in the description ("classifies and routes"), split it. Small functions compose; big ones hide bugs.
- Few parameters. More than ~4 positional arguments and callers start mixing them up — group related ones into a dict/dataclass or make the rest keyword-only.
- Return, don't print.
printis for humans at the edge;returnis for code. A function that prints can't be tested, reused or composed. - Don't repeat yourself. Two copies of the same logic will drift — extract the shared part into a function both call.
6.2 Pure functions and side effects#
A pure function produces output determined only by its inputs — no reading the clock, files, network, or global state, and no mutating its arguments:
def label_for(score): # pure: same score -> same label, always
if score is None:
return "unknown"
if score >= 90:
return "excellent"
if score >= 70:
return "ok"
return "needs work"
print(label_for(95), label_for(72), label_for(None))excellent ok unknownPure functions are trivially testable (call it, check the result) and safely cacheable. Side effects — printing, writing files, calling APIs, mutating shared state — are necessary but should be pushed to the edges: a pure core that computes, wrapped by a thin impure shell that does I/O. The ticket classify_ticket/priority/route are pure; main() is the impure edge that prints. This is the single most useful design habit in the whole path — 03.10 and 01B.8 build testing on it.
6.3 Idempotence and error handling at the boundary#
An operation is idempotent when doing it again has no further effect: the end state after one call and after a hundred calls is the same. Idempotence is not the same thing as purity (a pure function like label_for(95) is repeatable because it depends only on its input; an idempotent function may well change state, as long as repeating it changes nothing more):
def close_ticket(ticket): # idempotent: closing twice == closing once
ticket["status"] = "closed"
def add_note(ticket, note): # NOT idempotent: every call adds another note
ticket["notes"].append(note)Why it matters to an AI engineer: networks and models fail halfway, so calls get retried (by your retry decorator, by an SDK, by a queue). A retried close_ticket is harmless; a retried "charge the card" or "send the email" is not, unless it is made idempotent — typically with an idempotency key that lets the receiver recognise a repeat (03.8, Part 11 covers it for LLM calls and tool side effects). Design for it: prefer computing a value over appending to shared state, and when a function does mutate, say so in the docstring.
For errors, the boundary rule: validate inputs once at the top, then assume they're good inside. Raise early with a clear message rather than returning None to signal failure — None is a legitimate value, and callers forget to check it:
def divide(a, b):
if b == 0:
raise ZeroDivisionError("cannot divide by zero")
return a / braise is how Python functions signal "this can't continue"; the caller's try/except (01A.8) decides what to do. Returning None for "not found" is fine if documented (def find(...) -> ticket | None); returning None for "error" is a bug factory.
6.4 doctest: documentation that runs#
The >>> examples in a docstring aren't decoration — they're doctests, real tests the standard library can execute:
def classify_ticket(text):
"""Classify free text into a routing label.
>>> classify_ticket("Cannot log in after reset")
'auth'
>>> classify_ticket("Invoice total looks wrong")
'billing'
>>> classify_ticket("Hello there")
'general'
"""
t = text.lower()
if "log in" in t or "login" in t or "password" in t:
return "auth"
if "invoice" in t or "charged" in t or "billing" in t:
return "billing"
return "general"Save the snippet above as check.py and run python3 -m doctest check.py — it prints nothing when every example passes, and a diff showing expected vs actual when one fails. That silence is the pass signal:
$ python3 -m doctest check.py
$ echo "exit: $?"
exit: 0Doctests are perfect for pure functions with obvious input/output — they keep the docstring honest because a stale example fails loudly. They can't replace real tests for I/O, randomness or complex state (01B.8 owns pytest), but for classify_ticket-style functions they're free, always run, and self-documenting.
6.5 Assert self-checks and a pytest preview#
Before expensive work, a function can verify its own assumptions cheaply — selfcheck asserts against the classify_ticket you defined in 6.4:
def selfcheck():
assert classify_ticket("my invoice is wrong") == "billing"
assert classify_ticket("cant login") == "auth"
assert classify_ticket("just saying hi") == "general"
print("selfcheck passed")
selfcheck()selfcheck passedassert raises AssertionError if the assumption breaks — a fast "did I break the basics?" gate before main() runs. The ticket module uses exactly this under if __name__ == "__main__": (Part 8). For real testing — fixtures, parametrized cases, mocking, coverage — 01B.8 Testing with pytest is the next step; asserts and doctests are the on-ramp.
Part 7: The built-in function toolkit#
Reference
Python's built-ins are the functions you'll call most — learn them once and they replace a hundred lines of loops.
7.1 abs, all, any, min, max and sum#
print(abs(-7), abs(-7.5), abs(3))
nums = [2, 4, 6, 8]
print(all(n % 2 == 0 for n in nums))
print(any(n % 2 == 0 for n in nums))
print(all(n > 10 for n in nums))
print(all([]), any([]))7 7.5 3
True
True
False
True Falseall(...)is True only if every item is truthy;any(...)if at least one is. Both take any iterable — the generator expressions above are a preview (01A.5 owns them).- Empty input:
all([])isTrue,any([])isFalse— vacuous truth. "All zero items are even" is trivially true; "any item is even" needs at least one.
min/max take key= and default=:
words = ["fig", "banana", "apple", "cherry"]
print(min(words, key=len), max(words, key=len))
print(min(words), max(words))
tickets = [
{"id": "T-1", "points": 3},
{"id": "T-2", "points": 9},
{"id": "T-3", "points": 5},
]
hottest = max(tickets, key=lambda t: t["points"])
print("hottest:", hottest["id"], hottest["points"])
empty = []
print(max(empty, default=None))
try:
max(empty)
except ValueError as e:
print("ValueError:", e)fig banana
apple fig
hottest: T-2 9
None
ValueError: max() iterable argument is emptymax(iterable) on an empty iterable raises ValueError — pass default= when empty is legal. key=lambda t: t["points"] picks the dict field to compare.
sum adds an iterable, with an optional start:
print(sum([1, 2, 3]), sum([1, 2, 3], start=10))
print(sum([[1], [2]], [])) # [] + [1] + [2] — works on lists too!6 16
[1, 2]sum isn't just for numbers — start can be any object supporting +, so sum(lists, []) concatenates. Beware float sums: 0.1 + 0.2 precision is 01A.2's IEEE-754 lesson; for money use Decimal or integer cents.
7.2 sorted, map, filter and zip#
xs = [3, 1, 2]
s = sorted(xs)
print("sorted:", s, "| original:", xs)
xs.sort()
print("after .sort():", xs)
print("sort returns:", xs.sort())
print(sorted(words, key=len, reverse=True))sorted: [1, 2, 3] | original: [3, 1, 2]
after .sort(): [1, 2, 3]
sort returns: None
['banana', 'cherry', 'apple', 'fig']sorted() returns a new list; .sort() sorts in place and returns None — xs = xs.sort() is the classic bug. map and filter return lazy iterators (convert with list() to see them):
up = map(str.upper, ["a", "b", "c"])
print(type(up).__name__)
print(list(up))
long_words = filter(lambda w: len(w) > 3, words)
print(list(long_words))
pairs = zip(["a", "b", "c"], [1, 2, 3])
print(list(pairs))
print(list(zip([1, 2, 3], ["a", "b"])))map
['A', 'B', 'C']
['banana', 'apple', 'cherry']
[('a', 1), ('b', 2), ('c', 3)]
[(1, 'a'), (2, 'b')]map(fn, iterable) applies fn to each item; filter(fn, iterable) keeps items where fn is truthy. They're the pre-comprehension way to transform/filter — readable for simple cases, but 01A.5 shows why comprehensions usually win. zip pairs items and stops at the shortest (the [1,2,3]×["a","b"] case dropped the 3).
7.3 len, isinstance, getattr and callable#
print(len("hello"), len([1, 2, 3]), len({"a": 1}))
print(isinstance(5, int), isinstance(True, int), isinstance("5", int))
print(isinstance(5.0, (int, float)))
from types import SimpleNamespace
user = SimpleNamespace(name="Ada", role="engineer")
print(getattr(user, "name"))
print(getattr(user, "age", "unknown"))
print(hasattr(user, "role"), hasattr(user, "age"))
setattr(user, "role", "admin")
print(user.role)
print(callable(len), callable(42))5 3 1
True True False
True
Ada
unknown
True False
admin
True Falseisinstance(True, int)isTrue—boolis a subclass ofint(01A.2). Checktype(x) is boolif you need to exclude it.isinstance(x, (int, float))accepts a tuple of types.getattr(obj, "name", default)reads an attribute with a fallback — the defensive way to read SDK response objects, which are attribute-access objects (Pydantic models in 01B.6).hasattr/setattrare its siblings.callable(x)tells you ifxcan be called — functions, classes,functools.partialobjects all pass.
7.4 Choosing the right tool#
| You want to... | Use | Not |
|---|---|---|
| Check all/any items | all/any with a genexp |
a manual for + flag |
| Find min/max by a field | max(xs, key=fn) |
sort-then-take-first |
| Transform each item | comprehension or map |
append-in-a-loop (usually) |
| Keep items matching a test | comprehension or filter |
append-in-a-loop (usually) |
| Pair two lists | zip (+strict=True in 3.10+) |
index arithmetic |
| Sum numbers | sum |
manual accumulator |
| Check a type | isinstance |
type(x) == T (misses subclasses) |
The pattern: built-ins first, loops when the built-in can't express it. A for loop that appends to a list is a comprehension waiting to happen (01A.5).
Part 8: The ticket-triage running example#
Deep-dive
This lesson's piece of the module-wide support-ticket toolkit: three functions that take ticket dicts and produce labels, priorities and routes — pure functions a later lesson wraps in files, classes and tests.
"""triage.py — classify, prioritise and route support tickets (stdlib only)."""
from collections import Counter # preview: 01A.4 covers collections properly
TICKETS = [
{"id": "T-1001", "subject": "Cannot log in after password reset",
"body": "The login page loops back to sign-in every time.", "status": "open"},
{"id": "T-1002", "subject": "Invoice total looks wrong",
"body": "We were charged twice for March.", "status": "open"},
{"id": "T-1003", "subject": "API returns 500 on /v1/chat",
"body": "Started right after yesterday's deploy.", "status": "open"},
{"id": "T-1004", "subject": "How do I export my data?",
"body": "GDPR data-export request.", "status": "open"},
{"id": "T-1005", "subject": "Refund for cancelled plan",
"body": "Cancelled in January but still billed in February.", "status": "pending"},
{"id": "T-1006", "subject": "Slow responses in EU region",
"body": "p95 latency doubled since Tuesday.", "status": "open"},
{"id": "T-1007", "subject": "Login issue from last month",
"body": "Already fixed by the customer.", "status": "closed"},
{"id": "T-1008", "subject": "URGENT: production is down",
"body": "All customers report errors on every endpoint.", "status": "open"},
]
def classify_ticket(text):
"""Classify free text into a routing label.
>>> classify_ticket("Cannot log in after reset")
'auth'
>>> classify_ticket("Invoice total looks wrong")
'billing'
>>> classify_ticket("The site is down for everyone")
'infra'
>>> classify_ticket("Hello there, just saying hi")
'general'
"""
t = text.lower()
if "log in" in t or "login" in t or "password" in t or "sign in" in t:
return "auth"
if "invoice" in t or "charged" in t or "billing" in t or "refund" in t:
return "billing"
if "500" in t or "error" in t or "down" in t or "outage" in t:
return "infra"
return "general"
PRIORITY = {"infra": 4, "auth": 3, "billing": 2, "general": 1}
def priority(ticket):
"""Return an integer priority for a ticket dict (higher = sooner)."""
if ticket["status"] == "closed":
return 0
label = classify_ticket(ticket["subject"] + " " + ticket["body"])
return PRIORITY[label]
def route(ticket):
"""Route a ticket to a team name using structural pattern matching."""
label = classify_ticket(ticket["subject"] + " " + ticket["body"])
status = ticket["status"]
urgent = "urgent" in ticket["subject"].lower()
match (label, status, urgent):
case ("infra", "open", True):
return "sre-oncall"
case ("infra", "open", False):
return "sre-queue"
case ("billing", "open" | "pending", _):
return "finance"
case ("auth", "open", _):
return "account-team"
case (_, "closed", _):
return "archive"
case _:
return "triage"
def summarise(tickets):
"""Count tickets per label and per queue. Returns two Counters."""
by_label = Counter()
by_queue = Counter()
for t in tickets:
label = classify_ticket(t["subject"] + " " + t["body"])
by_label[label] += 1
by_queue[route(t)] += 1
return by_label, by_queue
def main():
rows = []
for t in TICKETS:
label = classify_ticket(t["subject"] + " " + t["body"])
rows.append((t["id"], label, priority(t), route(t)))
rows.sort(key=lambda r: (-r[2], r[0])) # priority desc, then id
for tid, label, prio, queue in rows:
print(f"{tid} {label:<8} p{prio} -> {queue}")
by_label, by_queue = summarise(TICKETS)
print("\nby label:", dict(sorted(by_label.items())))
print("by queue:", dict(sorted(by_queue.items())))
if __name__ == "__main__":
assert classify_ticket("cannot log in") == "auth"
assert classify_ticket("refund my money") == "billing"
assert classify_ticket("nothing in particular") == "general"
assert priority(TICKETS[0]) == 3
assert route(TICKETS[7]) == "sre-oncall"
main()Save as triage.py and run python3 triage.py:
T-1003 infra p4 -> sre-queue
T-1008 infra p4 -> sre-oncall
T-1001 auth p3 -> account-team
T-1002 billing p2 -> finance
T-1005 billing p2 -> finance
T-1004 general p1 -> triage
T-1006 general p1 -> triage
T-1007 auth p0 -> archive
by label: {'auth': 2, 'billing': 2, 'general': 2, 'infra': 2}
by queue: {'account-team': 1, 'archive': 1, 'finance': 2, 'sre-oncall': 1, 'sre-queue': 1, 'triage': 2}Read it as the pieces you've learned assembled: classify_ticket is an if/elif keyword chain (1.1) that leans on or (1.3); priority is an early return plus a dict lookup; route is a match on a tuple — sequence patterns of literals, an or-pattern "open" | "pending", wildcards _, and a guard-free ordering where ("infra", "open", True) must precede ("infra", "open", False); main is the impure edge that sorts by key=lambda and prints. The asserts under __name__ == "__main__" are the 6.5 self-check — they run only when the file is executed directly, not when imported.
python3 -m doctest triage.py exits silently — every >>> example in classify_ticket's docstring passes. 01A.9 will teach triage.py to read tickets from a CSV instead of the literal list, 01A.4 deepens the dicts, and 01A.6 turns the dicts into Ticket dataclasses.
Common mistakes#
The gallery — each snippet below is real, deterministic stdlib Python:
The mutable default. tags=[] looks like "a fresh empty list each call" — it isn't. Defaults are evaluated once at def time, so every call that omits tags shares the same list:
def add_tag(tag, tags=[]):
tags.append(tag)
return tags
print(add_tag("urgent"))
print(add_tag("billing"))
print(add_tag("vip"))['urgent']
['urgent', 'billing']
['urgent', 'billing', 'vip']The fix is the None sentinel — if tags is None: tags = [] inside the body (§3.3). This bites hardest in long-running processes: a cache={} default silently grows forever.
Late binding in closures. A lambda created in a loop captures the variable i, not its value — by call time the loop is done and i is 2:
funcs = [lambda: i for i in range(3)]
print("late binding:", [f() for f in funcs])
funcs = [lambda i=i: i for i in range(3)]
print("early binding:", [f() for f in funcs])late binding: [2, 2, 2]
early binding: [0, 1, 2]lambda i=i: i binds the current value as a default argument at creation time (§4.2). The same trap bites any loop that builds handlers or callbacks.
Assignment makes a name local — UnboundLocalError. count += 1 inside bump looks like it updates the global count; Python sees the assignment and treats count as local everywhere in the function, so the read on the right of += hits an unbound local:
count = 10
def bump():
count += 1
return count
bump()Traceback (most recent call last):
File "l3_shadow.py", line 7, in <module>
bump()
~~~~^^
File "l3_shadow.py", line 4, in bump
count += 1
^^^^^
UnboundLocalError: cannot access local variable 'count' where it is not associated with a valueThe fix is global count (or return the new value and assign at the call site — usually better). This is LEGB in action: assignment creates a local unless you say otherwise (§4.1).
Forgetting return. A function that only computes returns None — silently:
def broken_add(a, b):
a + b # computed, then thrown away
print("broken_add returns:", broken_add(2, 3))broken_add returns: NoneAnd print is not return: result = print_sum(2, 3) captures None, not 5 (§3.4).
range off-by-one. range's stop is excluded — range(5) gives 0–4, range(1, 6) gives 1–5. "Tickets 1 through 5" needs range(1, 6):
print(list(range(5))) # 0,1,2,3,4 — misses 1, adds unwanted 0
print(list(range(1, 6))) # 1,2,3,4,5[0, 1, 2, 3, 4]
[1, 2, 3, 4, 5]Same rule as slicing's s[a:b] — stop is one past the last you want (§2.2).
Common misconceptions#
| Misconception | Reality |
|---|---|
"and/or return True or False." |
They return one of the operands — "" or "x" gives "x", 0 and f() never calls f(). Only not returns a real bool. |
"if x: checks for None." |
It checks truthiness — 0, "", [], {} are all falsy. if x is not None: is the None-check; if x: is the "has useful content" check. |
"a < b < c means (a < b) and (a < c)." |
It means a < b and b < c, with b evaluated once. |
"else on a loop runs when the loop is empty." |
It runs whenever break didn't — including empty loops and normal completion. It's "no break happened", not "nothing iterated". |
| "Default arguments are fresh each call." | They're evaluated once at def time — a mutable default ([], {}) is shared across calls. Use None + build inside. |
"return a, b returns two things." |
It returns one tuple (a, b) that unpacks at the call site. |
"A function without return returns nothing." |
It returns None — silently. x = f() gives x is None. |
"x = xs.sort() sorts xs." |
.sort() returns None and sorts in place — x becomes None. Use sorted(xs) for a new list. |
"zip pads the shorter list." |
It stops at the shortest, silently dropping items. strict=True (3.10+) raises instead. |
| "Closures capture values." | They capture variables — all lambdas in a loop see the final value (late binding). Bind with lambda i=i: .... |
"@decorator is magic syntax." |
It's fn = decorator(fn) — a function call that rebinds the name. |
"assert validates input." |
python -O strips every assert — it's for invariants, not validation. Use if/raise. |
| "Recursion is always cleaner than a loop." | It costs a stack frame per call and dies at ~1000 depth (RecursionError). Loops for iteration; recursion for recursive problems. |
"isinstance(True, int) is False." |
bool subclasses int, so it's True — check type(x) is bool to exclude booleans. |
Key takeaways#
if/elif/elsebranches on truthiness;and/orreturn operand values and short-circuit; chained comparisons share the middle operand; the conditional expressionx if c else ypicks a value.match/case(3.10+) routes by shape — literals, sequences, mappings, class patterns,|alternatives, guards — first match wins,_is the wildcard.foriterates any iterable;range/enumerate/zip/reversed/sortedcover the daily cases.ziptruncates silently;sortedcopies while.sort()returnsNone.while+break/continue/elsehandles unknown trip counts; the loop-and-a-half (while True+break) reads cleanly; never mutate a list while iterating it.- Functions: positional/keyword, defaults,
*args,**kwargs, keyword-only (*) and positional-only (/) parameters, plus*/**unpacking at call sites;returnhands back values (tuples unpack), noreturnmeansNone. Never a mutable default — useNone+ build inside. - Scope is LEGB; closures remember enclosing variables (late binding is the gotcha);
nonlocal/globalassign outward; functions are first-class — pass, store, return them. - Decorators are
fn = decorator(fn); write them with an innerwrapper(*args, **kwargs)+@functools.wraps;@retry(times=3)is a decorator factory (three levels). functools.cachememoises pure functions;yieldmakes generators (lazy, one item at a time — 01A.5 owns them).- Design: small single-purpose functions, return don't print, pure core + impure edges,
doctestfor docstring examples,assertfor invariants. - Built-ins:
all/any/min/max/sum/sorted/map/filter/zip/isinstance/getattr— reach for them before writing a loop.
Where you'll use this in the AI path#
Every LLM call you'll write is functions and control flow. The specific skills come back immediately:
| Skill from this lesson | Where it is used next |
|---|---|
| Function signatures → JSON schemas | 03.5 Part 2: a tool function's parameters become the schema the model sees; 08A.6 Part 1 designs those signatures deliberately |
match/case routing |
Part 8 router; the same dispatch shape appears in 03.5 tool-name routing and 08A.2 agent loops |
| Closures & callbacks | 08A.2 §6.4 approver callback; 03.9 §4.4 on_progress; 03.11 Part 9 hooks — all closures passed as arguments |
| Decorators | @beta_tool 08A.2 §5.1; @workflow/@task 11A.1 §3.4; Modal @app.function 11C.6 §6.2; @cache 06.2 §5.3 |
| Retry decorator | 01B.9 builds the real one; 03.8 Part 8 applies it to LLM calls |
Generators / yield |
03.3 §2.5 SSE parser yields events; 01A.5 owns the full topic |
| Pure functions / testing | 03.10 and 01B.8 test exactly the pure-core/impure-edge split from 6.2 |
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Control flow | Deciding which code runs: if, loops, match |
| Truthiness | Whether a value counts as true in a condition (falsy: False, None, 0, "", empty containers) |
| Short-circuit | and/or returning early — the right side may never run |
| Chained comparison | a < b < c meaning a < b and b < c, middle evaluated once |
| Conditional expression | x if cond else y — an if that produces a value |
| Structural pattern matching | match/case routing by shape, not just value (Python 3.10+) |
| Pattern / guard / wildcard | A case shape / an extra if on a match / case _ catch-all |
| Iterable | Anything you can for over (list, string, dict, range, generator...) |
range |
Produces integer sequences; stop is excluded |
enumerate |
Yields (index, item) pairs in a loop |
zip |
Pairs items from multiple iterables; stops at shortest |
sorted / .sort() |
New sorted list / in-place sort returning None |
break / continue / loop else |
Exit loop / skip iteration / runs if no break |
| Loop-and-a-half | while True + break for "do, then check" |
| Accumulator | A variable carrying running state through a loop |
| Parameter vs argument | Names in def / values passed at call |
| Positional / keyword / default | Passed by position / by name / optional with a default |
*args / **kwargs |
Collect extra positional / keyword args |
| Argument unpacking | f(*seq) / f(**dict) spreading a sequence or dict into a call |
Keyword-only (*) / positional-only (/) |
Must be named / cannot be named |
| Mutable default argument | Shared default object — the [] trap; use None |
Return value / None |
What return hands back / implicit return of functions without return |
| Docstring | The string after def; documentation + help() + doctests |
| Doctest | >>> examples in docstrings run as tests |
| Scope / LEGB | Where names resolve: Local, Enclosing, Global, Builtins |
| Closure | A function remembering its defining scope's variables |
| Late binding | Closures capture variables, not values — loop gotcha |
nonlocal / global |
Assign in enclosing / module scope |
| First-class function | A function usable as a value (pass, store, return) |
lambda |
Tiny anonymous function, one expression |
functools.partial |
Pre-bind some arguments of a function |
Recursion / RecursionError |
Function calling itself / depth-limit error (~1000) |
Memoisation / functools.cache |
Caching results by arguments |
Generator / yield |
Lazy function producing one value at a time |
| Decorator | fn = decorator(fn) — a function wrapping a function |
functools.wraps |
Copies __name__/__doc__ onto a wrapper |
| Decorator factory | @retry(times=3) — a function returning a decorator |
| Pure function / side effect | Output depends only on inputs / observable external effect |
| Idempotent | Repeating the operation leaves the same end state as doing it once (close_ticket yes, add_note no) |
assert |
Invariant check; stripped by python -O |
isinstance / getattr / callable |
Type check / attribute read with default / can-it-be-called |
All terms are also collected in the glossary.
Exercises#
Run every snippet — the solutions are real, runnable code. Solutions are inside each <details> block; outputs were produced on Python 3.14 and are deterministic.
- The
or-default trap (1.3). A config dict may hold"retries": 0, which is a valid setting meaning "don't retry".config.get("retries") or 3silently turns it into 3. Writeretries_safe(config)that returnsconfig["retries"]when present (even if 0), else 3. Verify{"retries": 0}gives 0.
Solution
def retries_safe(config):
value = config.get("retries")
return 3 if value is None else value
print(retries_safe({"retries": 0})) # 0
print(retries_safe({})) # 30
3- Chained comparisons (1.4). Predict
tick(1) < tick(2) < tick(3)vstick(1) < tick(2) and tick(2) < tick(3)in terms of how many timestick(2)runs, then confirm by running both and printingcalls.
Solution
calls = []
def tick(x):
calls.append(x)
return x
print(tick(1) < tick(2) < tick(3), calls) # True [1, 2, 3]
calls.clear()
print(tick(1) < tick(2) and tick(2) < tick(3), calls) # True [1, 2, 2, 3]True [1, 2, 3]
True [1, 2, 2, 3]The chained form evaluates the middle operand once; the and form twice.
- Extend
handle()(1.6). Add a["mute", user]case that returns"muting {user}", and a guarded case["set", key, value] if key in ALLOWED(defineALLOWED = {"theme", "lang"}) returning"set {key}={value}". Add a second["set", key, _]case after it that returns"cannot set {key}". Test"mute ada","set theme dark","set root x", and the malformed"mute"and"set theme"— which cases catch each, and why does the order of the twosetcases matter?
Solution
ALLOWED = {"theme", "lang"}
def handle(command):
match command.split():
case ["status"]:
return "ok"
case ["restart", service]:
return f"restarting {service}"
case ["help", *topics]:
return f"help: {', '.join(topics) if topics else 'everything'}"
case ["mute", user]:
return f"muting {user}"
case ["set", key, value] if key in ALLOWED:
return f"set {key}={value}"
case ["set", key, _]:
return f"cannot set {key}"
case _:
return "unknown command"
for cmd in ["mute ada", "set theme dark", "set root x", "mute", "set theme"]:
print(f"{cmd!r:18} -> {handle(cmd)}")'mute ada' -> muting ada
'set theme dark' -> set theme=dark
'set root x' -> cannot set root
'mute' -> unknown command
'set theme' -> unknown command"set root x" matches the shape ["set", key, value] but fails the guard (root is not in ALLOWED), so matching falls through to the next case. If the unguarded ["set", key, _] case came first it would catch every three-word set command and the guarded case could never run. "mute" and "set theme" have the wrong number of words, so neither sequence pattern fits and case _ answers.
- Fix the modify-while-iterating bug (2.5). Rewrite the buggy
for x in items: if x > 2: items.remove(x)so it actually removes everything> 2— build a new list, don't edit in place.
Solution
def keep_small(items, limit):
kept = []
for x in items:
if x <= limit:
kept.append(x)
return kept
print(keep_small([1, 2, 3, 4, 5], 2)) # [1, 2][1, 2]for...elsefind (2.4). Writefind_index(items, target)that returns the index of the first match or-1, usingenumerate+break+else(nofoundflag).
Solution
def find_index(items, target):
for i, x in enumerate(items):
if x == target:
break
else:
return -1
return i
print(find_index(["a", "b", "c"], "b")) # 1
print(find_index(["a", "b", "c"], "z")) # -11
-1- Mutable default (3.3).
add_tagfrom the lesson leaks state between calls. Rewrite it so three separate calls return independent lists, while still letting a caller pass their own list.
Solution
def add_tag(tag, tags=None):
if tags is None:
tags = []
tags.append(tag)
return tags
print(add_tag("urgent"), add_tag("billing"), add_tag("vip"))['urgent'] ['billing'] ['vip']- Multiple return values (3.4). Write
split_name(full)returning(first, last); a single-word name returns(name, ""). Unpack at the call site and print both parts.
Solution
def split_name(full):
parts = full.split()
if len(parts) == 1:
return parts[0], ""
return parts[0], parts[-1]
first, last = split_name("Ada Lovelace")
print(first, "|", last) # Ada | Lovelace
first, last = split_name("Cher")
print(first, "|", last or "(none)") # Cher | (none)Ada | Lovelace
Cher | (none)- Closures and late binding (4.2). Write
make_tagger(prefix)returning atag(text)closure that prepends[prefix]. Then explain why[lambda: i for i in range(3)]gives[2,2,2]and fix it.
Solution
def make_tagger(prefix):
def tag(text):
return f"[{prefix}] {text}"
return tag
warn = make_tagger("WARN")
info = make_tagger("INFO")
print(warn("disk almost full"))
print(info("job finished"))
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs]) # [2, 2, 2] — shared variable
funcs = [lambda i=i: i for i in range(3)]
print([f() for f in funcs]) # [0, 1, 2] — bound at creation[WARN] disk almost full
[INFO] job finished
[2, 2, 2]
[0, 1, 2]- A counting decorator (5.2). Write
count_callsthat attaches acallsdict to the wrapped function soping.calls["n"]reports how many times it ran. Use@functools.wraps.
Solution
from functools import wraps
def count_calls(fn):
calls = {"n": 0}
@wraps(fn)
def wrapper(*args, **kwargs):
calls["n"] += 1
return fn(*args, **kwargs)
wrapper.calls = calls
return wrapper
@count_calls
def ping():
return "pong"
ping(); ping(); ping()
print("ping calls:", ping.calls["n"])ping calls: 3partialandcache(4.3, 4.5). Usefunctools.partialto makesquare/cubefrompower(base, exp). Then@cacheaslow_double(n)that appends to aworklist — show it's computed once for repeated calls.
Solution
from functools import partial, cache
def power(base, exp):
return base ** exp
square = partial(power, exp=2)
cube = partial(power, exp=3)
print(square(7), cube(2)) # 49 8
work = []
@cache
def slow_double(n):
work.append(n)
return n * 2
print(slow_double(21), slow_double(21), slow_double(21))
print("computed for:", work) # [21]49 8
42 42 42
computed for: [21]- Built-ins on tickets (7.1–7.4). Given
tickets = [{"id","points","status"}, ...](three dicts), useall/anyto check statuses,max(..., key=)for the top ticket, andsorted(..., key=)for ordering — no manual loops.
Solution
tickets = [
{"id": "T-1", "points": 3, "status": "open"},
{"id": "T-2", "points": 9, "status": "open"},
{"id": "T-3", "points": 5, "status": "closed"},
]
print("all open?", all(t["status"] == "open" for t in tickets))
print("any closed?", any(t["status"] == "closed" for t in tickets))
print("top ticket:", max(tickets, key=lambda t: t["points"])["id"])
print("sorted:", [(t["id"], t["points"]) for t in sorted(tickets, key=lambda t: t["points"])])all open? False
any closed? True
top ticket: T-2
sorted: [('T-1', 3), ('T-3', 5), ('T-2', 9)]sla_hourswithmatch(1.6). Writesla_hours(ticket)returning hours by(label, status):("infra","open")→1,("auth","open")→4, any closed→0, else→24.
Solution
def sla_hours(ticket):
match (ticket["label"], ticket["status"]):
case ("infra", "open"):
return 1
case ("auth", "open"):
return 4
case (_, "closed"):
return 0
case _:
return 24
print(sla_hours({"label": "infra", "status": "open"})) # 1
print(sla_hours({"label": "billing", "status": "pending"})) # 24
print(sla_hours({"label": "infra", "status": "closed"})) # 01
24
0doctest(6.4). Add a docstring with two>>>examples to a function of your choice, then runpython3 -m doctest file.py— confirm it prints nothing on success, then break an example on purpose and see the failure diff.
Solution
def is_adult(age):
"""Return True if age is 18 or over.
>>> is_adult(18)
True
>>> is_adult(17)
False
"""
return age >= 18python3 -m doctest file.py prints nothing when both examples pass; change True to False in the docstring and it prints a diff showing expected vs got.
- Reading a traceback (3.1). This function fails — find and fix the bug:
def greet(name):
return "Hello, " + name + "!"
print(greet(42))Solution
TypeError: can only concatenate str (not "int") to strname is an int; + can't join str and int. Two ways to fix it — convert explicitly or let the f-string do it:
def greet(name):
return f"Hello, {name}!"
print(greet(42)) # Hello, 42!Hello, 42!- Assert self-check (6.5). Write a
selfcheck()for theclassifyfunction below using threeasserts, and call it underif __name__ == "__main__":.
def classify(text):
t = text.lower()
if "invoice" in t or "billing" in t:
return "billing"
if "login" in t or "password" in t:
return "auth"
return "general"Solution
def selfcheck():
assert classify("my invoice is wrong") == "billing"
assert classify("cant login") == "auth"
assert classify("just saying hi") == "general"
print("selfcheck passed")
if __name__ == "__main__":
selfcheck()selfcheck passedCheck yourself#
- What does
"" or "fallback"return, and why?"fallback"—orreturns the first truthy operand, or the last if all falsy;""is falsy. - Why does
config.get("x") or 3lose a legitimate0?ortreats0as falsy and returns the fallback3instead of the configured0. Use an explicitis not Nonecheck. - How many times is the middle operand evaluated in
a < b < c?Once —a < b < cmeansa < b and b < cwithbevaluated a single time. - What's the difference between an
ifstatement and a conditional expression?ifis a statement that runs blocks;x if c else yis an expression that produces a value and can be assigned or passed. - In
match, what doescase _do, and what does a bare name likecase x:do?case _is the wildcard catch-all (likeelse).case x:is a capture — it bindsxto whatever value, not a comparison. - Why does
for x in items: items.remove(x)skip elements?Removing an item shifts the rest left; the iterator's index then skips the element that moved into the removed slot. - When does a loop's
elseclause run?When the loop completes without hittingbreak— including empty iterables and normal exhaustion. - Why is
def f(tags=[])dangerous, and what's the fix?The[]default is created once atdeftime and shared across calls, accumulating state. Fix:tags=Nonethentags = []inside. - What does a function return if it has no
return?None— silently. - What does
@functools.wrapspreserve, and what breaks without it?__name__,__doc__and other metadata; without it the wrapper hides the original's identity, breakinghelp(), tracebacks and introspection. - Explain late binding with
[lambda: i for i in range(3)].All three lambdas share the same loop variablei; by call time it's 2, so all return 2. Fix:lambda i=i: ibinds the value at creation. - What's the recursion limit, and what error do you get past it?1000 (
sys.getrecursionlimit()); past it you getRecursionError: maximum recursion depth exceeded. - Why should
@cacheonly decorate pure functions?The cache keys on arguments only — a function reading clock/files/global state would return stale cached results. - What's the difference between
sorted(xs)andxs.sort()?sorted(xs)returns a new sorted list leavingxsunchanged;xs.sort()sorts in place and returnsNone. - Why is
isinstance(True, int)True?boolis a subclass ofintin Python, soTruepasses anintcheck.
Further resources#
- Python Tutorial — More Control Flow Tools:
for,while,break/continue/else,range,match. - Python Tutorial — Functions: parameters,
*args/**kwargs, docstrings,lambda. - The Python Language Reference —
matchand PEP 634: the full pattern syntax. - Expressions — comparisons and boolean ops: chained comparisons, short-circuit values.
functools:cache,lru_cache,wraps,partial.doctest: running docstring examples as tests.sys.getrecursionlimitand the assert statement.- Built-in functions:
all,any,min,max,sum,sorted,zip,isinstance,getattr.
← 01A.2 — Numbers, Strings and Text | Module 01A overview | 01A.4 — Core Data Structures: Lists, Tuples, Dictionaries and Sets →