A Function is a named, organized block of reusable code that performs a single, specific task. Functions are defined using the `def` keyword:
def calculate_cylinder_volume(radius, height):
"""Calculates the geometric volume of a cylinder.
Parameters:
radius (float): Radius of the circular base.
height (float): Perpendicular height of cylinder.
Returns:
float: Calculated volume (pi * r^2 * h).
"""
import math
volume = math.pi * (radius ** 2) * height
return volume # Explicit return statement
The `return` Statement Mechanics
- Terminates function execution immediately and passes values back to the caller.
- Returning Multiple Values: A function can return multiple values separated by commas. Python automatically bundles them into an immutable tuple:
def min_max(numbers): return min(numbers), max(numbers) # Returns tuple (min_val, max_val) low, high = min_max([4, 1, 9, 2]) # Tuple unpacking! - Void Functions: If a function reaches the end of its body without executing a `return` statement (or executes a bare `return`), it implicitly returns the special literal `None`.