Skip to content
BIASED

Functions

Block 1 of 7~3 min

Giving code a name

The topic Control flow ended with programs long enough to repeat themselves. Here is a typical case: the mean training loss and the mean validation loss, computed by the same loop written twice.

train = [0.9, 0.6, 0.3]
val = [1.2, 0.8]
total = 0
for loss in train:
    total += loss
train_mean = total / len(train)
total = 0
for loss in val:
    total += loss
val_mean = total / len(val)
print(train_mean, val_mean)
0.6 1.0

Every copy is a place for a bug to differ, and a fix has to be made in every copy. The reader also has to notice that the two blocks do the same thing. A function writes the computation once, gives it a name, and turns the part that varies, the list, into an input.

def mean(values):
    total = 0
    for v in values:
        total += v
    return total / len(values)
 
print(mean([0.9, 0.6, 0.3]), mean([1.2, 0.8]))
print(mean)
0.6 1.0
<function mean at 0x10acdf5e0>

The rule. def name(parameters): followed by an indented block creates a function object and binds the name to it, just as an assignment would. The body does not run yet. A call, mean([...]), runs the body. return expression ends the call, and the value of the expression becomes the value of the call. The last line shows that mean is an ordinary object; the hexadecimal number is its address in memory and changes from run to run.

The names in the definition, values, are parameters. The values in a call, the two lists, are arguments. A call binds each parameter to an argument.

A function that reaches the end of its body without return, or stops at a bare return, returns None:

def report(epoch, loss):
    print(f"epoch {epoch}: loss {loss}")
 
r = report(3, 0.45)
print(r)
epoch 3: loss 0.45
None

report has a side effect, printing, and returns nothing useful. mean returns a value and prints nothing. Prefer the second kind: a value can be printed, tested, stored or passed on, while a printed line can only be read.

Answers are saved on the server and tied to this browser until you sign in.

Go deeper — optional

Code and labs do not count toward the main percentage or the certificate.

  • Function: calculate a discountoptional

    Real Python in your browser with result checks and a stop button. Device-local self-check; does not affect certificates.

    ~8 min · any device · Read this topic's notes.

    Open practice