Functions, modules, and type hints

3.15.2

Write reusable functions, define clear inputs and return values, and organize related code.

On this page

Parameters and return values

def defines a function. Arguments can be passed by position or by keyword when the signature permits. A function with no explicit return value returns None. Type annotations help tools and readers understand the interface.

def line_total(quantity: int, unit_price: float, *, discount: float = 0.0) -> float:
    return quantity * unit_price * (1 - discount)

print(line_total(4, 2.5, discount=0.1))
Example output
9.0

Default arguments and scope

Python evaluates default arguments when the function is defined. If the default should be a fresh list each call, use None and create the list inside the function. Assigning a name inside a function normally makes it local.

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

print(add_item("Tea"), add_item("Cake"))
Example output
['Tea'] ['Cake']

Import modules

A module groups Python definitions. Import a module to use its public names. In a script, the __name__ check keeps command-line entry code from running when the file is imported.

import math

def main():
    print(math.ceil(14 / 3))

if __name__ == "__main__":
    main()
Example output
5

Official references