Lesson · Functions
Function Fundamentals
51 min readFunction Fundamentals
Functions package behavior behind a name and an interface. They are objects in their own right, which lets Python pass them around, store them, decorate them, and return them.
Learning goals
- Write a function with
def, give it parameters, and return a result withreturn. - Trace a call: how argument values bind to parameter names, when the body runs, and where the return value goes.
- Explain why a function that never executes
returnstill produces a result, namelyNone. - Store a function in a variable or a list and call it through that name.
- Say which names are local to one call and why the next call starts fresh.
Mental model
A function is a value produced by def, and a call is the transaction that runs its body: arguments flow in, parameters hold them for the duration, the locals vanish when the call ends, and exactly one object comes back. When no return executes, that object is still produced, and its value is None. Because the function is just an object, any name bound to it, including a list element, can drive the same call.
A function is a value; a call is a transaction
arguments in, one result out, locals gone
Mental model
the same mechanism as a compact list
def area(width, height): creates a function object, binds the name ↓ operation = area a second name for the same object ↓ operation(3, 4) call: 3 binds to width, 4 binds to height ↓ body runs in a fresh local scope ↓ return width * height one result object travels back to the caller
Core idea
Two mechanisms organize this lesson: def builds a function object and binds a name to it, and a call moves values between caller and callee, from arguments into parameters and back out through one return object. Everything else, including the default result of None, locals that live only for one call, and functions stored in lists, follows from those two facts.
def
def is the statement that creates a function object: it compiles the body, records the parameter list as the function's calling signature, and binds the function's name in the current namespace. Defining a function executes none of the body; the code inside runs only when a call is made. The name is a plain binding, so it can be rebound or pointed at another callable later.
Calling functions
A call evaluates the callable expression and argument expressions, binds arguments to parameters, then executes the callable. A call either returns a value or exits by raising an exception.
Parameters
Parameters are the names listed in the def line that receive the caller's argument values when the function is called. Each call creates a fresh local binding for every parameter, so assignments to a parameter never leak to the caller or to the next call. A parameter without a default must be given an argument, or the call raises TypeError before the body runs.
Return values
The return statement ends the current function call and supplies one result object to the caller. Returning multiple comma-separated expressions creates one tuple result.
Multiple returns
Python returns one object from a function. Comma-separated expressions create a tuple, which callers can unpack into multiple names.
None return
A function that reaches the end without return, or executes bare return, returns None. Use that convention for procedures whose purpose is a side effect.
Local variables
Names assigned inside a normal function are local unless declared global or nonlocal. Each function call gets its own local execution state.
Function objects
Defining a function creates a function object and binds its name. That object can be stored, passed, inspected, decorated, or called later.
Functions as values
Functions are ordinary objects, so code can pass them as arguments, store them in containers, and return them from other functions. This enables strategy selection without large conditional blocks.
Walkthrough
def area(width, height):creates a function object and binds the namearea; none of the body runs until something calls it.operation = areabinds a second name to that same object, sooperation(3, 4)fillswidthwith3andheightwith4and returns12toprint.functions = [str.upper, str.lower]stores two built-in callables without calling them; the loop calls each one on"Python", so the first iteration printsPYTHONand the second printspython.- Predict before running: what
operation(3, 4)hands toprintif the body computeswidth * heightbut thereturnkeyword is missing.
Experiments to try
- Delete the
returnfromareaand print the call result; then put it back as a barereturnand compare the two outputs. - Add
height = 0as the first line ofarea's body, define a differentheightbefore the call, and print both after: the assignment inside the function never reaches the outer name. - Bind
alias = area, callalias(2, 5), and checkalias is area; both names produce the same result because they point at one function object. - Write
def min_max(values): return min(values), max(values), printtype(min_max([3, 1, 4])), then unpacklo, hi = min_max([3, 1, 4])and print both.
Common mistakes
- Forgetting
return: the function computes the value, falls off the end, and hands the callerNone, so the failure usually surfaces later as aTypeErrorwhen thatNonereaches arithmetic. - Expecting
defto run the body: definingareaonly creates the function object and binds its name, which is why a file of definitions prints nothing until something calls them. - Calling with the wrong number of arguments, as in
area(3)whenheighthas no default: binding fails before the first line of the body runs, and theTypeErrornames the parameter that found no value. - Assuming
operation = areacopies or calls the function: assignment binds another name to the same object, so every name runs the one body and shares its code.
Practice: Easy
- Call
operation(3, 4)andarea(3, 4)and confirm both produce12; then printoperation is areaand explain theTruein one sentence. - Change the first argument to
2.5and callarea(2.5, 4); print the result and itstypeto see why the product became afloat. - Delete the
returnfromarea, run the script, and write down exactly what the firstprintline shows; restore thereturnafterwards.
Practice: Medium
- Add a
perimeter(width, height)function, storeareaandperimeterin a list, and loop over the list calling each with(3, 4)while printingfn.__name__next to the result. - Rewrite
areato return(width * height, 2 * (width + height))and unpack the pair at the call site; explain why the function still returns exactly one object. - Write
apply_twice(fn, value)returningfn(fn(value))and test it withstr.upper,str.lower, and a function of your own that adds one to a number.
Practice: Hard
- Build an operator dispatcher: four functions (
add,subtract,multiply,divide), a dictionary from operator strings to those functions, andcompute(op, a, b)that looks the operator up and calls it; define whatcomputereturns for an unknown operator before implementing it. - Design the contract for
divide(a, b)whenb == 0: choose between returningNoneand raising, document the choice in a docstring, and write one call that follows the contract and one that tests the boundary. - Turn the worked example into a small report: keep
functions = [str.upper, str.lower], add a third callable of your own, and have the loop print each callable's name, result, and result type; state which attribute every callable must expose for the report to work.
Lesson checklist
- I can write a
defwith parameters, call it, and trace each argument into its parameter. - I can explain why a function without an executed
returnproducesNone, and when that is intended. - I can store a function in a variable or a list and call it through that name.
- I can say which names are local to one call and why the next call starts clean.
Remember
`def` creates a function object, a call binds argument values to parameters and runs the body in a fresh local scope, and `return` hands one result object back to the caller, with `None` as the outcome when no return executes. Because the function is an object like any other, other names and containers can reference it and drive the same call.
Interview angles
What is the main purpose of **def**?+
def creates a function object, records its parameter list as the calling signature, and binds the function's name in the current namespace; the body does not run until a call is made. The name is an ordinary binding, so it can be pointed at another callable later.
What should you pay attention to when using **Calling functions**?+
A call evaluates the callable expression and argument expressions, binds arguments to parameters, then executes the callable. A call either returns a value or exits by raising an exception.
How does **Parameters** fit into this lesson?+
Parameters are the names in the def line that receive the caller's argument values when the function is called. Each call creates fresh local bindings for them, so assignments never leak to the caller or to the next call. A parameter with no default must be given an argument, or the call raises TypeError before the body runs.
Why does a function that computes a value still hand the caller `None`?+
Because control reached the end of the body without executing a return, and Python ends every such call by producing None. The computation happened, but nothing was handed back, so the mistake usually appears later as a TypeError when that None reaches arithmetic.