Quick Reference: Functions
Module 9 Cheat Sheet
Basic Function Syntax
def function_name(parameters):
"""Docstring describing the function."""
# function body
return value
| Part | Description |
|---|---|
def | Keyword that starts a function definition |
function_name | Name in snake_case, should start with a verb |
(parameters) | Input variables the function accepts |
: | Colon ends the function header |
| Docstring | Triple-quoted string documenting the function |
return | Sends a value back to the caller |
Parameters and Arguments
| Type | Syntax | Example |
|---|---|---|
| Positional parameter | def f(a, b): | f(1, 2) |
| Default parameter | def f(a, b=10): | f(1) or f(1, 20) |
| Keyword argument | (at call site) | f(a=1, b=2) |
| *args | def f(*args): | Collects extra positional args into tuple |
| **kwargs | def f(**kwargs): | Collects extra keyword args into dict |
Order: positional → defaults → *args → **kwargs
Return Values
| Pattern | Code |
|---|---|
| Return single value | return result |
| Return multiple values | return a, b (returns a tuple) |
| No return statement | Function returns None |
| Early return | if error: return None |
| Unpack return values | x, y = func() |
Scope Rules (LEGB)
| Scope | Where | Accessible |
|---|---|---|
| Local | Inside the current function | Only inside that function |
| Enclosing | Inside an outer (enclosing) function | Inner functions can read it |
| Global | Module (file) level | Everywhere (read); use global to write |
| Built-in | Python's built-in names | Always available |
Common Patterns
| Pattern | Code |
|---|---|
| Function with docstring | def f(): """Does X.""" |
| Guard clause | if bad: return None |
| Accumulator | total = 0; for x in items: total += x; return total |
| Boolean function | def is_valid(x): return x > 0 |
| Flexible args | def f(required, opt="default", *args, **kwargs): |
Best Practices
- Name functions with verbs in
snake_case - Always include a docstring
- Keep functions short and focused on one task
- Prefer
returnoverprint(let the caller decide what to do with the result) - Avoid using
global— pass data through parameters instead - Do not shadow built-in names (
list,str,print, etc.)