15.Functions I: Defining & Calling
Functions package reusable behavior behind a name. They reduce duplication, improve readability, and make testing easier. This chapter covers how to define functions, parameter kinds you will use every day, return values, calling styles (positional vs keyword), annotations and docstrings, multiple return values, and practical patterns.
1. What Is a Function?
A function is a named block of code you can call to perform a task. In Python, functions are first-class objects (they can be stored in variables, passed to other functions, etc.), but in this part we focus on definition and calling.
- Encapsulate logic once; call many times with different inputs.
- Improve readability via meaningful names and parameters.
- Enable unit testing by isolating behavior.
2. Defining Functions — Syntax
Use the def statement with a name, parameter list in parentheses, and an indented body:
# Basic definition
def greet():
print(‘Hello!’)
# Define with parameters and a return value
def area_of_circle(radius):
pi = 3.1415926535
return pi * radius * radius
- Indentation defines the function body (4 spaces by convention).
- Return ends the function and passes a value back (default is None if omitted).
3. Calling Functions
Call by writing the function name followed by parentheses. Provide arguments in positional or keyword form:
# Calling without arguments
greet() # Hello!
# Calling with positional argument
print(area_of_circle(2)) # 12.566370614
# Calling with keyword argument (recommended for clarity when many params)
print(area_of_circle(radius=3))
- Use keyword arguments when the call site benefits from clarity.
- Avoid mixing many positional arguments; prefer keywords beyond a few simple parameters.
4. Parameters: Positional, Keyword, Defaults
Core parameter kinds you will use in daily code. (Advanced kinds like *args/**kwargs and keyword-only are covered in Functions II.)
# Positional-or-keyword parameters and defaults
def rectangle_area(width, height=1):
return width * height
rectangle_area(5) # 5 (height uses default 1)
rectangle_area(5, 2) # 10
rectangle_area(width=5, height=3) # 15
- Choose parameter names that describe expected values (width, height, radius).
- Do not use mutable defaults like [] or {}; cover in Functions II for safe patterns.
5. Return Values, None, and Multiple Returns
A function returns the value after return. If there is no return (or it returns without value), Python returns None.
# Implicit None return
def log_message(msg):
print(msg)
# returns None implicitly
# Multiple return values are actually a single tuple you can unpack
def min_max(values):
return min(values), max(values)
lo, hi = min_max([3, 1, 4])
print(lo, hi) # 1 4
- Returning a tuple and unpacking is idiomatic for multiple results.
- Prefer explicit return values over relying on implicit None for clarity.