Skip to main content
A Python function is a first-class object that encapsulates a block of parameterized statements. It is defined using the def keyword, executes within its own local lexical scope upon invocation, and yields a value to the caller via the return statement, implicitly evaluating to None if no return is specified.

Base Syntax

Functions are declared with the def keyword, followed by an identifier, a parenthesized parameter list, and a colon. The function body must be indented.

Parameter and Argument Mechanics

Python supports highly flexible parameter binding mechanisms. Arguments can be passed positionally or by keyword.
  • Default Parameters: Assigned at function definition time, not at execution time. (Note: Using mutable objects like list or dict as defaults results in the same object being shared across all calls).
  • Arbitrary Positional Arguments (*args): Captures excess positional arguments into a tuple.
  • Arbitrary Keyword Arguments (**kwargs): Captures excess keyword arguments into a dict.

Parameter Modifiers (Python 3.8+)

You can enforce how arguments are passed using special syntax markers / and *.

Return Mechanics

The return statement terminates function execution and passes an object back to the caller.

Scope and Namespaces (LEGB Rule)

When a variable is referenced inside a function, Python resolves the name using the LEGB rule, searching in this exact order:
  1. Local: Names assigned within the function.
  2. Enclosing: Names in the local scope of any enclosing functions (closures).
  3. Global: Names assigned at the top-level of the module.
  4. Built-in: Names preassigned in the built-in names module.
To modify variables outside the local scope, Python provides specific keywords:
  • global: Binds a local identifier to the module-level namespace.
  • nonlocal: Binds a local identifier to the nearest enclosing lexical scope (used in nested functions/closures).

First-Class Object Characteristics

Functions in Python are instances of types.FunctionType. They possess attributes (like __name__ and __doc__) and can be treated as data. This allows for higher-order functions:
  • Assigned to variables.
  • Passed as arguments to other functions.
  • Returned from other functions.

Lambda Functions

Python supports anonymous, inline functions via the lambda keyword. Lambdas are restricted to a single expression and cannot contain statements or annotations. The result of the expression is implicitly returned.
Tired of Poor Python Skills? Fix That With Deep Grasping!Learn More