Topic 54 of 64
Function Definitions
Overview
Functions in Python are first-class objects — they can be passed as arguments, returned from other functions, and stored in variables. Understanding function definition syntax, defaults, and return values is fundamental to clean Python code.
Syntax
python
# Basic function
def greet(name: str) -> str:
return f"Hello, {name}!"
# Default parameters
def power(base: float, exp: float = 2) -> float:
return base ** exp
# No return value (returns None implicitly)
def log_message(msg: str) -> None:
print(f"[LOG] {msg}")
# Multiple return values (returns a tuple)
def divmod_custom(a: int, b: int) -> tuple[int, int]:
return a // b, a % bCommon Pitfalls
- Default mutable arguments (like def func(items=[])) are shared across all calls — use None as default and initialize inside the function.
- Parameters with defaults must come after parameters without defaults.
- Interview tip: Functions are objects — you can assign them to variables, store in lists, and pass as callbacks: sorted(data, key=my_func).
Real-World Example
Utility function with defaults for building API query strings
example
python
def build_query(
endpoint: str,
page: int = 1,
limit: int = 20,
sort: str = "created_at",
order: str = "desc",
) -> str:
return f"{endpoint}?page={page}&limit={limit}&sort={sort}&order={order}"
url = build_query("/api/users", limit=10)
print(url) # /api/users?page=1&limit=10&sort=created_at&order=desc