Why functions
Without functions, you’d copy the same lines everywhere you need them, and fix every copy when there’s a bug. A function lets you write the code once, give it a name, and call it from anywhere. The name also documents intent: spread(scores) says more than six lines of loop.
Anatomy
def spread(values): # name and parameters
low, high = min_max(values)
return high - low # the result
gap = spread([3, 9, -2]) # a call, with an argument
- Parameters are the names in the definition:
values. - Arguments are the actual values passed in a call:
[3, 9, -2]. returnends the function and hands a value back to the caller. A function without one returns nothing:Nonein Python,undefinedin JavaScript.
Returning more than one thing
The example finds the smallest and largest value in a list, which is two results. Each language has its own way to return both, and its own way to say “there were no values”:
def min_max(values):
"""Return the smallest and largest value, as a pair."""
if not values:
raise ValueError("min_max() needs at least one value")
smallest = largest = values[0]
for v in values[1:]:
if v < smallest:
smallest = v
if v > largest:
largest = v
return smallest, largest
def spread(values):
low, high = min_max(values) # call it, then unpack the two results
return high - low// Return the smallest and largest value, as a pair.
function minMax(values) {
if (values.length === 0) throw new RangeError('minMax() needs at least one value');
let smallest = values[0];
let largest = values[0];
for (const v of values.slice(1)) {
if (v < smallest) smallest = v;
if (v > largest) largest = v;
}
return [smallest, largest];
}
function spread(values) {
const [low, high] = minMax(values); // call it, then unpack the two results
return high - low;
}// minMax returns the smallest and largest value. Go functions can return
// several results; ok is false when there are no values.
func minMax(values []int) (smallest, largest int, ok bool) {
if len(values) == 0 {
return 0, 0, false
}
smallest, largest = values[0], values[0]
for _, v := range values[1:] {
if v < smallest {
smallest = v
}
if v > largest {
largest = v
}
}
return smallest, largest, true
}
func spread(values []int) (int, bool) {
low, high, ok := minMax(values) // call it, then unpack the results
return high - low, ok
}// Returns the smallest and largest value as a pair, or None for no values.
fn min_max(values: &[i32]) -> Option<(i32, i32)> {
let (&first, rest) = values.split_first()?;
let (mut smallest, mut largest) = (first, first);
for &v in rest {
if v < smallest {
smallest = v;
}
if v > largest {
largest = v;
}
}
Some((smallest, largest))
}
fn spread(values: &[i32]) -> Option<i32> {
let (low, high) = min_max(values)?; // call it, then unpack the pair
Some(high - low)
}- Python returns a tuple and unpacks it with
low, high = .... An empty list raises an error. - JavaScript returns an array and destructures it with
const [low, high] = .... - Go has real multiple return values, plus an
okflag for the empty case. - Rust returns
Option<(i32, i32)>: either a pair orNone, and?passesNonestraight on.
Scope and the call stack
Variables created inside a function are local. They exist only during that call, and other functions can’t see them. Two calls to the same function each get their own copies.
That works because every call gets a fresh stack frame on the call stack, holding its parameters and locals. When the function returns, its frame is removed. A function that calls itself is recursion, and the stack is what keeps each call’s variables apart.
Common mistakes
- Forgetting to return. A function that computes a result but never returns it gives back
Noneorundefined. - Changing arguments by accident. Passing a list passes a reference to it, so changes inside the function show up outside.
- Using globals instead of parameters. A function that reads global state is hard to test and hard to reuse. Pass what it needs.
- Mutable default arguments in Python.
def f(items=[])shares one list across every call. UseNoneand create the list inside.
Check yourself
Check yourself
In def area(width, height), called as area(3, 4), what are 3 and 4?
Arguments are the values passed in a call. The parameters are the names width and height that receive them.
Check yourself
A function sets a local variable x = 5 and returns. What happens to x?
Locals live in the call’s stack frame, which is removed when the function returns. To keep the value, return it.
Sources
- Harold Abelson and Gerald Jay Sussman, Structure and Interpretation of Computer Programs, 2nd edition (1996), chapter 1.
- Robert C. Martin, Clean Code (2008), chapter 3, “Functions.”
Finished this page?
Your list