Python Functions
Functions Playbook
Python Functions
Functions are Python's unit of reuse. Master definitions, arguments, return types, lambdas, and recursion so you can break logic into testable units.
12
Concepts
8
Code samples
10+
Satellites
Defining functions
def greet(name: str) -> str:
return f"Hello {name}"
defintroduces the function.- Optional type hints describe parameter and return types.
returnends execution and sends a value back. Omitted return impliesNone.
Arguments
| Pattern | Example | Notes |
|---|---|---|
| Positional | def send(to, subject) | Order matters |
| Keyword | send(to="bob", subject="Hi") | Self-documenting |
| Default | def send(subject="Hi") | Evaluate defaults at definition time |
| Positional-only | def gcd(a, b, /) | Python 3.8+ syntax |
| Keyword-only | def connect(*, timeout=5) | Force explicit keyword usage |
*args and **kwargs
def log_event(event, *details, **meta):
...
*argscollects extra positional parameters as a tuple.**kwargscollects keyword arguments as a dict.
Multiple return values
Python returns tuples; you can unpack them elegantly:
def transform(record):
return record.id, record.score
identifier, score = transform(entry)
Lambdas
Anonymous, single-expression functions:
double = lambda x: x * 2
sorted(users, key=lambda user: user.last_login)
Use them for short callbacks. Prefer named functions for complex logic.
Recursion
def factorial(n: int) -> int:
if n <= 1:
return 1
return n * factorial(n - 1)
Add base cases to prevent infinite recursion. Python's recursion depth defaults to ~1000 calls—be mindful.
Scope & closures
- Variables defined inside functions are local.
- Use
nonlocalto modify variables in enclosing scopes, andglobalfor module-level names (sparingly). - Functions capture variables they reference:
def multiplier(factor):
def apply(value):
return value * factor
return apply
Documentation & testing
- Add docstrings describing arguments, returns, and exceptions.
- Use doctest or unit tests to codify expectations.
Next up in your learning path
Frequently Asked Questions
Why do my default arguments change between calls?
Default arguments evaluate once when the function is defined. If the default is a mutable object (like a list), it persists across calls. Use `None` and instantiate inside the function instead.
Should every function return a value?
Functions without an explicit return automatically return `None`. That's fine for procedures, but favor explicit returns so behavior is obvious.
How do I document functions?
Add docstrings describing arguments, returns, and raised exceptions. Pair them with type hints and tests. Tools like Sphinx can generate API docs automatically.