Defining and Calling Functions
Use thedef keyword to define a function, followed by a name, parentheses, and a colon. The indented block beneath is the function body.
Naming Conventions
Follow these rules for clear, Pythonic function names (snake_case):Parameters and Arguments
Parameters make functions flexible by accepting input values:The names in the function definition are called parameters. The actual values you pass when calling the function are called arguments.
Positional Arguments
By default, Python matches arguments to parameters by their position:Default Values
Give parameters default values to make them optional:Keyword Arguments
Pass arguments by name for clarity, in any order:Return Values
Usereturn to send a value back to the caller. Python exits the function immediately when it hits return:
Returning Multiple Values
Separate values with commas — Python wraps them in a tuple automatically:Flexible Arguments
*args — Variable Positional Arguments
Prefix a parameter with * to collect any number of positional arguments into a tuple:
**kwargs — Variable Keyword Arguments
Prefix a parameter with ** to collect any number of keyword arguments into a dictionary:
Combined Example
Positional-Only / and Keyword-Only * Parameters
Variable Scope & the LEGB Rule
Scope refers to which parts of your code can see a given variable. Python searches for variable names in this strict order:1
L — Local
Variables defined inside the current function.
2
E — Enclosing
Variables in any surrounding (outer) function scopes.
3
G — Global
Variables defined at the top level of the module.
4
B — Built-in
Python’s pre-loaded names like
len, print, range.global and nonlocal
Functions as First-Class Objects
Python functions are objects — you can assign them, pass them, and inspect their attributes:Lambda Functions
A lambda is a small, anonymous function that consists of a single expression:Closures
A closure is a nested function that remembers variables from its enclosing scope even after the outer function has finished:Decorators
A decorator is a higher-order function that wraps another function to extend its behaviour without modifying its source:Decorators with Arguments
Use*args and **kwargs so the decorator works with any function signature:
Generators
A generator produces values one at a time usingyield, consuming far less memory than returning a full list:
next() to retrieve values manually: