Functions: package an idea you can call
A function is a named recipe with its own scratch space. When you call it, a fresh scope opens (watch the call stack appear), it does its work on the arguments you pass, and it hands a value back with return. Here is the same job — find the largest number — done four ways.
Find the largest number in a list — written straight, with no function.
Functions — the same work, inline execution-derived · CPython
variables
state after line 1 runs
| variable | value |
|---|---|
nums | [3,9,4] |
noteNo function here — just the numbers, in the main program's own scope.
step 1 / 11
Click a line, drag the slider, or use the ← → keys.
What you are looking at
- Procedural — the work written straight, in the main program. It runs, but it lives in one scope, it is tied to this one list, and there is no call stack: nothing is "called".
- Idiomatic — the same work as a function. Step into the call and watch the call stack grow to
find_max(): it gets its own scope, the parameternumsholds the argument, andreturn besthands 9 back to the caller, whereanswercatches it. That hand-off is the entire point of a function. - Buggy — the same function, but with the
returnline missing. It computes the right answer, then falls off the end and hands backNone. Watchanswerend upNone— the work was done, but nothing came back. This is the single most common function bug. - Clever — Python already ships
max(). We call it and get 9, but it is built into the language, not Python we can trace, so there is nothing to step into.
Every value you see came from running each program under CPython's tracer — see how GlassBox stays honest.