How to Define a Function with Default Parameter Values in Python
This code demonstrates defining a Python function with default parameter values, showing how to call it with zero, one, or two arguments.
Python code
15 linesdef greet(name: str = "World", punctuation: str = "!") -> str:
"""Return a greeting message using default parameter values."""
message = f"Hello, {name}{punctuation}"
return message
if __name__ == "__main__":
# Call with no arguments – uses both defaults
print(greet())
# Call with one argument – uses default punctuation
print(greet("Python"))
# Call with both arguments – overrides both defaults
print(greet("Developer", "."))
Output
Hello, World!
Hello, Python!
Hello, Developer.
How it works
The greet function declares two parameters, name and punctuation, each with a default value. When you call the function without providing an argument for a parameter, Python automatically uses the default. This allows the function to be flexible—handling calls with anywhere from zero to two arguments. The default values are evaluated once at function definition time, which is fine for immutable types like strings. The function's type hints (name: str, -> str) improve readability and enable static checking.
Common mistakes
- Setting default parameters to mutable objects like lists or dictionaries, which can cause shared-state bugs.
- Forgetting that default arguments are evaluated only once, making them unsuitable for dynamic values like timestamps.
- Omitting type hints, making the function less self-documenting and harder to maintain.
Variations
- Use keyword arguments when calling to make the intent clear: `greet(name="Python", punctuation="?")`.
- Leverage `functools.partial` to create a new function with fixed defaults.
Real-world use cases
- Providing sensible defaults in a logging helper so callers can override log level only when needed.
- Building API client methods where optional query parameters default to a standard set.
- Creating test fixtures where most test cases use default setup, with occasional overrides.
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.