Glossary

Function

A function in Python is a named, reusable block of code defined with the def keyword. Functions accept zero or more parameters, execute a body of statements, and optionally return a value with the return statement (returning None implicitly if no return is reached). Functions are the primary unit of code reuse and abstraction in Python.

Python functions are first-class objects: they can be assigned to variables, passed as arguments, returned from other functions, and stored in data structures. This enables powerful patterns like callbacks, higher-order functions, and decorators. Functions can be defined inside other functions (nested functions) and can capture variables from their enclosing scope, creating closures.

Python supports several parameter-passing styles: positional arguments, keyword arguments, default values, variadic positional (*args), variadic keyword (**kwargs), and positional-only or keyword-only parameters (using / and * separators in the signature). The combination of these features gives Python functions exceptional flexibility. Every function should have a docstring — a string literal as the first statement of the body — that documents its purpose, parameters, and return value.

Related terms: Parameter, Argument, Return Value, Scope, Lambda

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.