A function packages a block of code under a name so it can be reused. Define one with def.
def greet(name):
message = f"Hello, {name}!"
return message
result = greet("Ada")
print(result)Hello, Ada!
The function has:
- A name:
greet. - A parameter:
name. - A body: the indented lines.
- A return value: the expression after
return.
Calling a function#
Calling means using the function name followed by parentheses:
print(greet("Grace"))Arguments are matched to parameters in order. The returned value replaces the call expression, so greet("Grace") becomes the string it returns.
Returning early#
return exits the function immediately:
def absolute(value):
if value < 0:
return -value
return value
print(absolute(-7)) # 7Code after a return in the same block is unreachable. Keep branches simple so every path is obvious.
Functions without a return#
If no return runs, the function returns None:
def show_total(items):
print(f"Total items: {len(items)}")
result = show_total([1, 2, 3])
print(result)Total items: 3 None
Prefer returning a value and letting the caller decide how to display it. Pure functions are easier to test and reuse.
Docstrings#
The first statement in a function can be a string that documents it:
def rectangle_area(width, height):
"""Return the area of a rectangle.
Both dimensions are expected to be non-negative numbers.
"""
return width * heighthelp(rectangle_area) displays the docstring. The description should explain behaviour, assumptions, and the meaning of parameters, not restate the code.
Type hints#
Optional annotations document expected types and support editors:
def average(numbers: list[float]) -> float:
return sum(numbers) / len(numbers)Python does not enforce annotations at runtime. They are documentation and tooling support, not validation. Use mypy or pyright for static checking.
Small functions#
Good functions have one clear job. Compare:
def process(values):
cleaned = [value.strip().lower() for value in values if value.strip()]
return sorted(set(cleaned))with a function that reads input, cleans data, computes statistics, prints a report, and writes a file. The first is easier to test and change.
Functions calling functions#
def is_even(number):
return number % 2 == 0
def count_evens(numbers):
return sum(1 for number in numbers if is_even(number))
print(count_evens([1, 2, 4, 7, 10]))3
Composing small functions keeps each piece readable and independently testable.
Practice#
Write three functions: is_prime(n), count_primes(limit), and print_primes(limit). The first returns a boolean, the second returns an integer, and the third prints the values. Notice how count_primes can reuse is_prime without duplicating logic.
