Topic 4 of 64
Functions
Overview
Python functions support default arguments, keyword arguments, *args, **kwargs, and type hints — making them incredibly flexible. Mastering these features is essential for writing professional Python code.
Syntax
python
# Basic function
def greet(name: str) -> str:
return f"Hello, {name}!"
# Default arguments
def create_user(name, role="viewer", active=True):
return {"name": name, "role": role, "active": active}
# *args (variable positional) and **kwargs (variable keyword)
def log(*args, level="INFO", **kwargs):
print(f"[{level}]", *args)
for key, val in kwargs.items():
print(f" {key}: {val}")
# Lambda (anonymous function)
square = lambda x: x ** 2
sorted_users = sorted(users, key=lambda u: u["name"])
# Type hints (strongly recommended)
def calculate_tax(income: float, rate: float = 0.3) -> float:
return income * rateCommon Pitfalls
- Never use mutable default arguments: def fn(lst=[]). The list is shared across calls. Use None and create inside.
- Keyword-only arguments (after *) must always be passed by name — they can't be positional.
- Interview tip: *args is a tuple, **kwargs is a dict inside the function. You can unpack with *list and **dict when calling.
Real-World Example
A flexible API response builder:
example
python
from typing import Any, Optional
def build_response(
data: Any,
message: str = "Success",
status: int = 200,
*, # force keyword-only arguments after this
meta: Optional[dict] = None,
paginated: bool = False
) -> dict:
response = {
"status": status,
"message": message,
"data": data,
}
if meta:
response["meta"] = meta
if paginated and isinstance(data, list):
response["count"] = len(data)
return response
# Usage
build_response(users, meta={"page": 1, "total": 50}, paginated=True)