TwiddleLab / Code / Build with Python
Functions That Call Functions
What you will learn
- Decomposition: split a big job into small named functions that call each other.
- Every call puts a card on the call stack with its own boxes; return takes it off and carries the value back.
- Variables inside a function are local: an x in a function is a different box from an x outside.
- f(g(x)) runs g first, then feeds its answer to f.
How the lesson goes
A password checker, written two ways. Find the digit check in each.
Tap the line that checks for a digit. A stopwatch times you.
is_valid calls two helpers. Which function finishes first?
Read the code, then tap a function.
Step through it. Watch the stack of cards.
A call puts a card on top. return takes it off.
Decomposition and the call stack.
Decomposition means splitting a job into small functions with clear names. Each one does one thing.
The call stack is a pile of cards. A call puts a new card on top with that function's own boxes; return takes the top card off and carries its value down to the caller.
Boxes made inside a function are local: they live on its card and disappear when it returns.
Run the stack yourself.
Before each call, drag the right card onto the stack. Before each return, drag the top card back.
Build is_valid from the two helpers.
A password is valid if it's long enough and has a digit. Put the lines in order; four tests run.
Two function machines in a row. Find x so the top chain gives 11.
The inner call runs first. Watch the other order too.
Password gauntlet: a hacker tries your is_valid.
For each password, tap pass or fail before your function runs.
Two boxes called x. Which one does print(x) show?
The program is paused inside bump. Tap the box line 6 will print.
A teaser: a function that calls itself.
How many cards will the stack hold at its tallest? Pin it, then Run.
Previous lesson: Debugging Like a Detective · Next lesson: Randomness and Simulation · Part of the course: Build with Python
Lessons are interactive and need JavaScript. Turn it on to play them.