Functions
def, parameters and arguments, defaults, keyword-only parameters, return values, docstrings and recursion.
Functions let you give a name to a chunk of logic and reuse it. They are the building blocks of every non-trivial program: they remove repetition, make code testable, and let you think about what something does without re-reading how it does it.
Defining and calling#
defstarts the definition, followed by the name and parameters in parentheses, then a colon.- The indented body runs only when the function is called.
returnsends a value back to the caller and exits the function immediately.
A function must be defined before the line that calls it runs — which is why definitions usually sit at the top of a file and the "main" code at the bottom.
Parameters vs arguments#
Parameters are the names in the definition; arguments are the values you pass. You can pass arguments by position or by keyword:
Keyword arguments make call sites self-documenting — connect(timeout=5) is clearer than connect(5).
Default values#
Parameters with defaults must come after those without.
The mutable-default trap
Default values are evaluated once, when the def runs — not on every call. A mutable default like a list is therefore shared between calls:
The safe pattern uses None as the default and creates a fresh object inside:
Keyword-only and positional-only parameters#
A bare * in the parameter list forces everything after it to be passed by keyword. This prevents confusing calls like create_user("ada", True, False):
Calling create_user("ada", True) would raise TypeError. (A / does the opposite: parameters before it are positional-only. You'll see it in the signatures of built-ins like len(obj, /).)
Return values#
A function can return any object — including several values at once, which Python packs into a tuple:
Prefer returning values over printing inside functions. A function that returns can be tested, reused and combined; one that prints can only print.
Docstrings and type hints#
A docstring — the string on the first line of the body — documents the function; help(area) and editors display it. Type hints (: float, -> float) tell readers and tools what to pass and expect. Python does not enforce them at runtime, but checkers like mypy and your editor use them to catch bugs. There's a full lesson on type hints later.
Functions are objects#
In Python a function is a value like any other: you can store it in a variable, put it in a dict, or pass it to another function. That's what makes sorted(words, key=len) work — len is passed in, not called.
This idea — functions taking and returning functions — powers callbacks, decorators and much of Python's elegance.
Recursion#
A function can call itself. Each call must move towards a base case that stops the recursion:
Recursion is natural for tree-shaped data (folders, nested JSON), but Python limits recursion depth to about 1000 calls, so use loops for long linear processes.
Designing good functions#
- Do one thing. If you need "and" to describe it, split it.
- Name it with a verb:
calculate_total,send_email,is_valid. - Keep it short — if it doesn't fit on a screen, it's probably doing too much.
- Avoid hidden inputs and outputs: take data as parameters and return results rather than reading or changing global variables.
Worked example: a small receipt module#
Common mistakes#
- Forgetting to call:
print(greet)prints<function greet at 0x...>; you needgreet("Ada"). - Printing instead of returning — then
total = add(2, 3)givesNone. - Code after
returnnever runs. - Mutable default arguments — use
None. - Too many positional parameters — use keyword-only parameters or group related data.
What's next#
You've seen that variables inside a function are separate from those outside. Next we'll explore exactly how that works: scope, the LEGB rule and closures.
Check your understanding
Quick quiz
1.What does a function return if there is no
returnstatement?2.In
def greet(name, excited=False):, what isexcited?3.Why is
def add(item, items=[]):a bad idea?
Finished reading?
Mark this lesson complete to track your progress.