Functions

Functions

Use def to name reusable behavior and return results.

return sends a value back to the caller. The caller can print it, store it, or pass it to another function.

Source

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

print(greet("Python"))

Output

Hello, Python.
nameDEF GREET(NAME):"Hello, " + name"Hello, Ada"
A function takes inputs, evaluates a body, and returns a value: `greet('Ada')` produces `'Hello, Ada'`.

Default arguments provide common values. Keyword arguments make it clear which option is being overridden.

Source

def format_total(amount, currency="USD"):
    return f"{amount} {currency}"

print(format_total(10))
print(format_total(10, currency="EUR"))

Output

10 USD
10 EUR

A function without an explicit return returns None. That makes side-effect-only functions easy to distinguish from value-producing ones.

Source

def log(message):
    print(f"log: {message}")

result = log("saved")
print(result)

Output

log: saved
None

Mutable default arguments are evaluated once when the function is defined, not on each call. The same list is shared across calls, so successive calls see each other's mutations. Use None as the sentinel and create a fresh container inside the body.

Source

def append_broken(item, items=[]):
    items.append(item)
    return items

print(append_broken("a"))
print(append_broken("b"))


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

print(append_fixed("a"))
print(append_fixed("b"))

Output

['a']
['a', 'b']
['a']
['b']

Notes

See also

Run the complete example

Example code

Expected output

Hello, Python.
10 USD
10 EUR
log: saved
None
['a']
['a', 'b']
['a']
['b']

Execution time appears here after you run the example.