Python Function Default Parameters Explained with Examples
Learn how to define Python functions with default parameter values and call them with fewer arguments than declared.
Python code
14 linesdef greet(name, greeting="Hello", punctuation="!"):
return f"{greeting}, {name}{punctuation}"
def calculate_area(length, width=1, unit="sq units"):
area = length * width
return f"Area: {area} {unit}"
if __name__ == "__main__":
print(greet("Alice"))
print(greet("Bob", "Hi"))
print(greet("Charlie", "Hey", "..."))
print(calculate_area(5))
print(calculate_area(5, 3))
print(calculate_area(4, 2, "cm²"))
Output
Hello, Alice!
Hi, Bob!
Hey, Charlie...
Area: 5 sq units
Area: 15 sq units
Area: 8 cm²
How it works
Default parameters let you define sensible fallback values so callers can omit those arguments. In greet("Alice"), the defaults greeting="Hello" and punctuation="!" are used automatically. When you pass only some arguments, Python fills the remaining ones from left to right using defaults. The calculate_area function shows defaults can also be non-string values like numbers. This pattern reduces repetitive code and makes functions more flexible to call.
Common mistakes
- Putting default parameters before non-default ones (SyntaxError)
- Using mutable defaults like `def f(x=[])` which share state across calls
- Forgetting that defaults are evaluated once at definition time, not each call
Variations
- Call functions using keyword arguments: `greet(name="Alice", greeting="Hello")`
- Use `None` as default and assign inside the function for mutable defaults
Real-world use cases
- Logging functions where log level defaults to INFO but can be overridden per call.
- API client methods with timeout or retry defaults that callers can customize.
- Configuration parsers with optional flags like pretty-print defaulting to False.
Sponsored
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.