Skip to content
UPEEC

Python Functions

Defining functions in Python: default and keyword arguments, *args/**kwargs, lambdas, decorators and generators.

Easy
Comments 0
def scale(value, gain=1.0, *, offset=0.0):
    """Return value * gain + offset."""
    return value * gain + offset

scale(2, 3)               # positional
scale(2, offset=1)        # keyword-only after *

Functions are first-class objects: you can pass them as arguments, return them and store them in variables. The text in triple quotes is a docstring, shown by help(scale).

Sub-topics (4)

*args and **kwargs

Accept any number of positional (*args) or keyword (**kwargs) arguments.

Easy♥ 0🔖 0💬 0

Lambda Functions

Small anonymous functions written in a single expression.

Easy♥ 0🔖 0💬 0

Decorators

A decorator wraps a function to add behaviour — like timing, logging or caching — without changing its code.

Intermediate♥ 0🔖 0💬 0

Generators

Functions that yield values one at a time, producing sequences lazily and saving memory.

Intermediate♥ 0🔖 0💬 0

Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.

Discussion (0)

Sign in or join free to ask questions and discuss this topic.