Functions

RequiredRequired

Juan Camilo ZúñigaBackend & data developer

A function names a piece of logic so you can reuse it and test it on its own.

def area(width, height):
    """Area of a rectangle."""
    return width * height

area(3, 4)   # 12

A function without return returns None. The string right after def is the docstring: help(area) shows it.

Arguments

def greet(name, greeting="Hello"):
    return f"{greeting}, {name}"

greet("Ada")                    # default greeting
greet("Ada", greeting="Hi")     # keyword argument, clearer at the call site

*args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dict.

The default value trap

Defaults are evaluated once, when the function is defined. A mutable default is shared between calls:

def add_item(item, items=[]):    # bug: the same list every time
    items.append(item)
    return items

def add_item(item, items=None):  # fix
    if items is None:
        items = []
    items.append(item)
    return items

Scope

Names assigned inside a function are local to it. Reading a global works, but reassigning one needs global; avoid it and pass values in and out instead. Small functions that take inputs and return outputs are the easiest to test.