Skip to content
Tactiverge

Python reference

Functions and return values

Also called: def · return · parameters · arguments · default argument

Definition

def name(parameters): defines a reusable block of code. Calling it runs the body with the given arguments, and return sends a value back to the caller.

Picture it

A function is a small machine with labelled inputs and one output. Naming a calculation once, testing it, then reusing it is how engineers stop copy-pasted formulas drifting apart. A function with no return statement returns None.

Worked example

What does led_resistor(5, 2.0, 0.015) return? def led_resistor(v_supply, v_f, i): return (v_supply - v_f) / i

  1. (5 − 2.0) / 0.015 = 3.0 / 0.015
  2. = 200.0

Answer200.0 (ohms).

✓ The number in this answer is recomputed from scratch by an automated test.

In Python

def led_resistor(v_supply, v_f, i):
    """Series resistor in ohms for an LED."""
    return (v_supply - v_f) / i

assert abs(led_resistor(5, 2.0, 0.015) - 200) < 1e-9

Common misconceptions

  • Misconception: print inside a function is not the same as return; printed values cannot be used by the caller.
  • Misconception: A mutable default such as def f(x=[]) is shared between calls.