Difficulty: Intermediate
Functions in Python are defined using the `def` keyword followed by the function name, parentheses containing any parameters, and a colon. The function body is an indented block of code that executes when the function is called. Functions allow you to encapsulate reusable logic, making your code modular, testable, and easier to maintain. Every Python function returns a value -- if no explicit `return` statement is provided, the function returns `None` by default.
The `return` statement exits the function and sends a value back to the caller. A function can have multiple `return` statements (for example, inside conditional branches), but only one executes per call. You can also return multiple values as a tuple by separating them with commas. This is a common Python idiom that leverages tuple unpacking to assign returned values to individual variables in a single line.
Docstrings are string literals placed as the very first statement inside a function body. They serve as the function's documentation and are accessible at runtime via the `__doc__` attribute or through the built-in `help()` function. The convention is to use triple-quoted strings, with the first line being a concise summary, optionally followed by a blank line and a more detailed description. Well-written docstrings make your code self-documenting and are essential for collaborative projects.
Default parameters allow you to specify fallback values for function arguments. When the caller omits those arguments, the defaults kick in. This is extremely useful for creating flexible APIs where most callers use common values but some need customization. Parameters with defaults must come after parameters without defaults in the function signature, or Python will raise a `SyntaxError`.
def add(a, b):
"""Return the sum of two numbers."""
return a + b
def is_even(n):
"""Check whether a number is even."""
return n % 2 == 0
print(add(3, 7))
print(is_even(4))
print(is_even(5))
The `add` function takes two parameters and returns their sum. The `is_even` function returns a boolean indicating whether the number is divisible by 2. Both functions use docstrings to describe their purpose.
def min_max(numbers):
"""Return both the minimum and maximum of a list."""
return min(numbers), max(numbers)
lowest, highest = min_max([4, 1, 8, 2, 9])
print(f"Min: {lowest}")
print(f"Max: {highest}")
Python allows returning multiple values separated by commas, which creates a tuple. The caller can use tuple unpacking to assign each value to a separate variable in one line.
def greet(name, greeting="Hello", punctuation="!"):
"""Build a greeting string with optional customization."""
return f"{greeting}, {name}{punctuation}"
print(greet("Alice"))
print(greet("Bob", "Hi"))
print(greet("Charlie", "Hey", "."))
The `greeting` and `punctuation` parameters have default values, so the caller can omit them. When provided, the caller's values override the defaults. Parameters with defaults must appear after those without.
def calculate_area(radius):
"""Calculate the area of a circle.
Args:
radius: The radius of the circle (non-negative number).
Returns:
The area as a float.
"""
import math
return math.pi * radius 2
print(round(calculate_area(5), 2))
print(calculate_area.__doc__.strip().split('\n')[0])
The docstring follows the Google style guide format with Args and Returns sections. Accessing `__doc__` at runtime retrieves the raw docstring, which tools like `help()` and documentation generators use.
def Keyword, return Statement, Docstrings, Default Parameters