Python Functions
Define reusable blocks of code with parameters, returns, and defaults
Overview
Functions encapsulate logic you want to reuse. Python functions are first-class objects—you can pass them as arguments, return them, and assign them to variables. Use def to define and return to send a value back to the caller.
Syntax / Usage
def greet(name, greeting="Hello"):
"""Return a greeting string."""
return f"{greeting}, {name}!"
# Positional and keyword arguments
greet("Ada")
greet("Ada", greeting="Hi")
# Arbitrary arguments
def summarize(*args, **kwargs):
return args, kwargs
summarize(1, 2, key="value")
# Lambda (anonymous one-liners)
double = lambda x: x * 2
Type hints (optional but recommended) document expected types without enforcing them at runtime.
Examples
Calculate order total with tax:
def order_total(subtotal: float, tax_rate: float = 0.08) -> float:
return round(subtotal * (1 + tax_rate), 2)
order_total(100) # 108.0
order_total(100, 0.1) # 110.0
Validate password length:
def is_valid_password(password: str, min_length: int = 8) -> bool:
return len(password) >= min_length
Common Mistakes
- Using mutable default arguments (
def f(items=[]):)—defaults are created once - Forgetting
returnyieldsNoneimplicitly - Shadowing built-ins like
sumormaxwith parameter names - Relying on global state instead of passing explicit parameters
See Also
python-variables python-decorators python-modules