Python · Chapter 7 of 21
Python functions: parameters, return values and type hints
14 min study · Examples checked with Python 3.14 and 3.15 ·
A function gives a name to a piece of work so you can run it again with different inputs. Good functions are small agreements: they say what they need, what they give back, how they fail and whether they change anything outside themselves. This chapter builds a few functions for a study tracker and uses them to cover parameters, return values, default arguments and type hints.
Define a function and return a result
def completion_percent(done: int, total: int) -> float:
"""Return how much of a course is finished, from 0 to 100."""
if total <= 0:
raise ValueError("total must be positive")
if not 0 <= done <= total:
raise ValueError("done must be between 0 and total")
return done / total * 100
print(completion_percent(3, 4)) # 75.0
print(completion_percent.__doc__) # Return how much of a course is finished, from 0 to 100.
def creates a function object and binds it to a name; the body runs only when the function is called. The names in the definition (done, total) are parameters; the values in a call (3, 4) are arguments. return ends the call and hands a value back. A function that finishes without return, or with a bare return, returns None.
The string right under the def line is the docstring. help(completion_percent) shows it, and so do editors. Write it as one sentence saying what the function returns or does; add details about arguments and errors when they are not obvious.
The function rejects impossible input by raising an exception instead of returning some odd value. Checking the bad cases first and returning early (“guard clauses”) keeps the main logic unindented and easy to read.
Return values, print at the edges
def progress_line(name: str, done: int, total: int) -> str:
return f"{name}: {completion_percent(done, total):.0f}% complete"
line = progress_line("Ada", 3, 4)
print(line) # Ada: 75% complete
print(line.upper()) # ADA: 75% COMPLETE
Because progress_line returns its text instead of printing it, the caller decides what happens next: print it, write it to a file, send it in a web response or compare it in a test. Printing inside a calculation ties it to the terminal forever. Functions whose job is a side effect, such as saving a file or sending an email, are fine; give them names that say so (save_report, send_reminder).
Positional, keyword and default arguments
Arguments can be passed by position or by name. Defaults make parameters optional. A bare * in the parameter list makes everything after it keyword-only; a / makes everything before it positional-only.
def format_progress(name, done, total, *, decimals=0, unit="%"):
value = completion_percent(done, total)
return f"{name}: {value:.{decimals}f}{unit}"
print(format_progress("Ada", 1, 3)) # Ada: 33%
print(format_progress("Joan", 1, 3, decimals=2)) # Joan: 33.33%
print(format_progress(total=3, done=2, name="Grace")) # Grace: 67%
def clamp(value, /, low, high):
return max(low, min(value, high))
print(clamp(120, 0, 100), clamp(-5, low=0, high=100)) # 100 0
Keyword-only parameters prevent unreadable calls like format_progress("Ada", 1, 3, 2, "pts"), where nobody remembers what 2 means. Positional-only parameters let you rename them later without breaking callers. Use these markers where they prevent a likely mistake, not on every function.
Default values are created once
A default value is evaluated when the def statement runs, not on every call. With an immutable default such as 0 or "%" that makes no difference. With a list or dictionary it does:
def add_topic_bad(topic, topics=[]):
topics.append(topic)
return topics
print(add_topic_bad("Python")) # ['Python']
print(add_topic_bad("Django")) # ['Python', 'Django'] (the same list again)
def add_topic(topic: str, topics: list[str] | None = None) -> list[str]:
topics = [] if topics is None else topics
topics.append(topic)
return topics
print(add_topic("Python"), add_topic("Django")) # ['Python'] ['Django']
Use None as the default and create the fresh object inside the function. Linters flag the bad version, but it is worth recognizing on sight.
Arguments are shared, not copied
Passing an object to a function gives the parameter a reference to the same object. Changing that object inside the function changes it for the caller; rebinding the parameter to something new does not.
def mark_done(progress: dict[str, int], name: str) -> None:
progress[name] = progress.get(name, 0) + 1 # mutates the caller's dict
def reset(progress: dict[str, int]) -> None:
progress = {} # rebinds a local name only
week = {"Ada": 2}
mark_done(week, "Ada")
reset(week)
print(week) # {'Ada': 3}
When a function should not change its input, say so in the name and work on a copy, or return a new value ({**progress, name: 1}). Functions that only compute a result from their arguments, without side effects, are called pure; they are the easiest to test and reuse.
Collect and spread arguments with * and **
def total_minutes(*sessions: int) -> int:
return sum(sessions)
def describe(name: str, **details: object) -> str:
extras = ", ".join(f"{k}={v}" for k, v in details.items())
return f"{name} ({extras})"
week = [30, 45, 25]
print(total_minutes(*week)) # 100
print(describe("Ada", course="Python", streak=4)) # Ada (course=Python, streak=4)
print(completion_percent(**{"done": 1, "total": 4})) # 25.0
In a definition, *sessions collects extra positional arguments into a tuple and **details collects extra keyword arguments into a dictionary. In a call, * spreads an iterable into positional arguments and ** spreads a dictionary into keyword arguments. This is how wrappers and decorators pass arguments through (chapter 8). In everyday functions, named parameters document themselves better than **kwargs.
Return several values and the empty case
A function can return a tuple, which the caller unpacks:
def summarize(scores: list[int]) -> tuple[int, float | None]:
if not scores:
return 0, None
return len(scores), sum(scores) / len(scores)
count, average = summarize([72, 85, 91])
print(count, round(average, 1)) # 3 82.7
print(summarize([])) # (0, None)
The empty case returns None for the average, because there is no average of nothing; returning 0 would make “no scores yet” look like “scored zero”. Once a result has more than two or three fields, return a dataclass (chapter 11) so callers use names instead of positions.
Type hints
The annotations in these examples (done: int, -> float, list[str] | None) are type hints. Python does not check them when the code runs: completion_percent("3", 4) still fails with an ordinary TypeError from the comparison inside, not because of the hint. Their value comes from tools. An editor uses them for completion, and a type checker such as mypy or pyright reports mismatched calls before you run anything. Frameworks like FastAPI read them to validate request data.
The common forms are built-in types (int, str), generic containers (list[int], dict[str, float], tuple[int, str]), unions with | (int | None for “an int or nothing”), and object when anything goes. Start by annotating function signatures; that is where hints help most.
Practice
Write discounted_price(price, *, discount=0.0) that returns the price after a discount between 0 and 1, rejects a negative price or an out-of-range discount with ValueError, and has a docstring and type hints. Format the result to two decimals in the caller, not inside the function.
Answer check: discounted_price(100, discount=0.2) returns 80.0, and discounted_price(100, 0.2) raises TypeError because discount is keyword-only. discount=1.5 raises ValueError. Write three assert lines that check these cases; they make a small first test (chapter 9 shows how to test that an exception is raised).
Summary
A function is an agreement: inputs, result, errors and side effects. Return values instead of printing, validate at the top, use keyword-only parameters for options, and never use a mutable default. Arguments are passed by reference, */** collect and spread arguments, and type hints document the agreement for tools and readers.