How to Use Default Parameter Values in Python Functions
Shows how to define and call Python functions with default parameter values, including overriding some or all defaults and using keyword arguments.
Python code
23 linesdef greet(name, greeting="Hello", punctuation="!"):
"""Return a greeting message using default parameters."""
return f"{greeting}, {name}{punctuation}"
if __name__ == "__main__":
# Using defaults
print(greet("Alice"))
# Overriding first default
print(greet("Bob", "Hi"))
# Overriding both defaults
print(greet("Charlie", "Hey", "."))
# Using keyword arguments
print(greet("Diana", punctuation="?"))
# Validating default behavior
assert greet("Alice") == "Hello, Alice!"
assert greet("Bob", "Hi") == "Hi, Bob!"
assert greet("Charlie", "Hey", ".") == "Hey, Charlie."
assert greet("Diana", punctuation="?") == "Hello, Diana?"
print("All assertions passed.")
Output
Hello, Alice!
Hi, Bob!
Hey, Charlie.
Hello, Diana?
All assertions passed.
How it works
Default parameters let you call a function with fewer arguments than its full signature, filling in missing values automatically. The defaults are evaluated when the function is defined, not each time it's called. You can override individual defaults by passing values positionally or by name with keyword arguments. Keyword arguments make it clear which parameter you're setting and let you skip earlier defaults. This pattern keeps functions flexible while avoiding repetitive code.
Common mistakes
- Using mutable defaults like lists or dicts, which persist between calls
- Putting parameters with defaults before required parameters in the signature
- Forgetting that keyword arguments must come after positional ones in a call
Variations
- Use *args and **kwargs to accept variable numbers of arguments with defaults
- Use functools.partial to fix default values at call time instead of definition time
Real-world use cases
- Building reusable log formatters where the log level and timestamp format have sane defaults.
- Constructing API client wrappers where retry counts and timeouts are optional via defaults.
- Creating configurable UI builders that accept optional style or behavior flags.
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.