Recursion
Not met yet
A recursive function solves a problem by calling itself on a smaller piece of it. To weigh a crate of parts and crates, add up the parts, and weigh each crate inside the same way. Every call has its own local variables, so an inner call's answer only reaches the outer call if it is returned and used. Anything built from smaller copies of itself, like crates in crates or a family tree, is a natural fit.
Try it
main.pyOutput
Press Run and what your program prints shows up here.
Easy to get wrong
- Thinks a recursive function handles one level of nesting but not a crate inside a crate inside a crate.
- Thinks a function can't call itself because it isn't finished being defined, so expects a NameError.
- Thinks a function that calls itself must go on calling itself for ever, even when each call is handed a smaller problem.
- Thinks a recursive call shares the caller's local variables, so the inner call's total adds into the outer one without being returned.
- Thinks returning a recursive call's answer is optional, as if calling the function again replaced the current call's result.