Home / Learn / Code for makers

Python functions explained: def, return, arguments and scope

New to this? Read from the top. Already know the basics? Jump to Going deeper for intermediate and advanced detail.

A Python function as a machine: arguments 512, vref 5.0 and bits 10 go in, the def body works out the volts, and return hands back 2.5
Beginner

A function is a named, reusable block of code. You give it some inputs, it does a job, and it hands back a result. Once a project grows past a page or so, functions are what keep it readable: instead of the same ten lines copied in four places, you write them once and call them by name. Everything here works the same in MicroPython on a Raspberry Pi Pico or ESP32.

Your first function

This one converts a raw analogue-to-digital converter (ADC) reading into volts. MicroPython's read_u16() returns 0 to 65,535, so by default it divides by 216 − 1:

def adc_to_volts(reading, vref=3.3, bits=16):
    """Convert a raw ADC reading to volts."""
    return reading * vref / (2 ** bits - 1)

print(adc_to_volts(32768))
print(adc_to_volts(512, vref=5.0, bits=10))
print(round(adc_to_volts(512, vref=5.0, bits=10), 2))

Output:

1.6500251773861294
2.5024437927663734
2.5
  • def starts the function, followed by its name and its parameters in brackets.
  • The body is everything indented underneath. Python uses the indent, not braces, to know where the function ends.
  • return hands a value back to whoever called the function, and ends the function there.
  • The text in triple quotes is a docstring. It's optional, but help(adc_to_volts) will show it, and so will most editors.

The values you pass in when you call it (32768, vref=5.0) are called arguments.

Default and keyword arguments

vref=3.3 gives the parameter a default, so you can leave it out. The second call above overrides both defaults for a 10-bit, 5 V Arduino-style ADC. Writing name=value in a call is a keyword argument: the order no longer matters and the call explains itself. adc_to_volts(512, bits=10, vref=5.0) does exactly the same thing.

Rules to remember: parameters with defaults must come after the ones without, and positional arguments must come before keyword ones in a call.

Returning more than one value

Separate the values with commas and Python returns them together as a tuple, which you can unpack straight into variables:

def min_max_avg(values):
    return min(values), max(values), sum(values) / len(values)

low, high, avg = min_max_avg([21.5, 22.0, 23.25, 22.75])
print(low, high, avg)

This prints 21.5 23.25 22.375.

The missing return

A function without a return line still returns something: the special value None. This is one of the most common beginner bugs:

def area(width, height):
    width * height          # works it out, then throws it away

print(area(3, 4))           # prints None

If a result comes out as None, or you get TypeError: unsupported operand type(s) for +: 'NoneType' and 'int', check the function actually returns its answer. Our guide to Python error messages covers that error and others.

Any number of arguments: *args

A parameter written with a star collects all the extra positional arguments into a tuple. Anything after it must be passed by keyword:

def describe(name, *readings, units="°C"):
    total = sum(readings)
    print(f"{name}: {len(readings)} readings, average {total / len(readings):.1f} {units}")

describe("Greenhouse", 18.2, 19.0, 19.6)
describe("Loft", 8.0, 7.5, units="°C")
Greenhouse: 3 readings, average 18.9 °C
Loft: 2 readings, average 7.8 °C

Local and global variables

Variables created inside a function are local: they exist only while that call runs and can't clash with names elsewhere. A function can read a variable from outside, but if it assigns to a name anywhere in its body, Python treats that name as local for the whole function. So this fails:

count = 0

def bump():
    count = count + 1    # UnboundLocalError

bump()

Python 3.13 reports UnboundLocalError: cannot access local variable 'count' where it is not associated with a value (older versions say "local variable 'count' referenced before assignment"). You could add global count as the first line of the function, but the cleaner fix is usually to pass the value in and return the new one: count = bump(count). Functions that only use their arguments are far easier to test and reuse.

The mutable default trap

Default values are created once, when Python runs the def line, not each time the function is called. With a number or a string that never matters. With a list or dictionary, every call shares the same object:

def add_reading(value, log=[]):     # the list is made ONCE, when def runs
    log.append(value)
    return log

print(add_reading(1))   # [1]
print(add_reading(2))   # [1, 2]  <- the same list again!

The standard fix is to default to None and create the list inside:

def add_reading(value, log=None):
    if log is None:
        log = []          # a fresh list on every call
    log.append(value)
    return log

print(add_reading(1))   # [1]
print(add_reading(2))   # [2]

Good habits

  • One job per function. read_sensor(), to_celsius() and log_reading() beat one giant do_everything().
  • Name it with a verb that says what it does: read_temperature, not temp.
  • Return values instead of printing them, so the caller can decide whether to print, log or plot.
  • Define before you call. Python runs top to bottom, so a function must be defined before the line that first calls it runs.

Testing a function

Small functions are easy to check with known answers. Water boils at 100 °C (212 °F), and −40 is the same on both scales, which makes them perfect test values:

def c_to_f(celsius):
    return celsius * 9 / 5 + 32

print(c_to_f(100))
print(c_to_f(-40))
print([round(c_to_f(t), 1) for t in (18.5, 21.0, 37.0)])

This prints 212.0, -40.0 and [65.3, 69.8, 98.6]. If you change the function later and those numbers change, you know you broke something. To loop over your readings, see Python for loops; to store them, lists and dictionaries.

Intermediate and advanced

Going deeper

Keyword-only and positional-only parameters

A bare * in the parameter list makes everything after it keyword-only: def move(steps, *, speed=100) must be called as move(200, speed=50), which stops two numbers being swapped by accident. A / does the opposite: parameters before it can only be passed by position. **kwargs collects any extra keyword arguments into a dictionary.

Type hints

def adc_to_volts(reading: int, vref: float = 3.3, bits: int = 16) -> float: documents what goes in and out. Python itself ignores hints when it runs, but editors and checkers such as mypy use them to catch mistakes before you run the code. MicroPython accepts the syntax but doesn't check it either.

Functions are objects

You can store a function in a variable or a dictionary and pass it to another function. sorted(readings, key=abs) passes the built-in abs function; a lambda is a one-line nameless function for the same job: sorted(sensors, key=lambda s: s["temp"]). A dictionary of functions makes a neat command menu: commands = {"on": led_on, "off": led_off} then commands[word]().

Closures

A function defined inside another one remembers the outer function's variables even after it has returned. def make_scaler(gain): return lambda x: x * gain gives double = make_scaler(2), and double(21) returns 42. Use nonlocal if the inner function needs to change one of those variables.

Recursion and its limit

A function can call itself, but CPython stops at a default depth of about 1,000 calls with RecursionError, and MicroPython runs out of stack much sooner on a microcontroller. On small boards, prefer a loop.

Sources

The main references behind this guide. Numbers we worked out ourselves, such as the code outputs, come from running the code.