Defining Functions
Writing reusable functions with def, return values, parameters, and docstrings.
2 min read
A function packages up a piece of logic so you can run it by name instead of copying the same code everywhere you need it. Python defines one with def.
The basic shape
def greet(name):
return f"Hello, {name}!"
message = greet("Ada")
print(message) # Hello, Ada!def starts the definition, greet is the function's name, name in parentheses is a parameter the function expects, and the indented block is its body. return sends a value back to whoever called the function — without it, the function returns None by default.
Parameters vs. arguments
The terms are related but distinct: a parameter is the name in the function's definition (name above); an argument is the actual value passed in when you call it ("Ada"). A function can take several:
def add(a, b):
return a + b
result = add(3, 5) # 8Functions without a return value
Not every function needs to hand back a value — some exist purely for their side effect, like printing:
def log_message(message):
print(f"[LOG] {message}")
log_message("Server started")Calling log_message(...) and trying to use its result would give you None, since there's no return statement. That's expected — this function's job is the print, not producing a value.
Docstrings
A string literal placed as the very first line of a function's body becomes its docstring — documentation that tools (and help()) can read back:
def area_of_circle(radius):
"""Return the area of a circle given its radius."""
return 3.14159 * radius ** 2
print(area_of_circle.__doc__)
# Return the area of a circle given its radius.For anything beyond a trivial one-liner, a docstring is the standard way to explain what a function does, what it expects, and what it returns — far more discoverable than a # comment above the def line.
Functions can return multiple values
Python lets a function return more than one value at once, by packing them into a tuple behind the scenes:
def min_and_max(numbers):
return min(numbers), max(numbers)
low, high = min_and_max([4, 1, 9, 2])
print(low, high) # 1 9Why bother
Beyond avoiding repetition, functions give a name to a piece of logic — area_of_circle(radius) is more self-explanatory at the call site than the raw formula would be, and it means fixing a bug or changing behavior only requires editing one place instead of hunting down every copy. The next lessons build on this with default values, keyword arguments, and short one-off functions written as lambdas.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.