How to Use Default Parameter Values in Python Functions
This code demonstrates how to define a Python function with default parameters and call it with varying numbers of arguments to see the defaults applied.
Python code
8 linesdef greet(name, greeting="Hello", punctuation="!"):
message = f"{greeting}, {name}{punctuation}"
print(message)
if __name__ == "__main__":
greet("Alice")
greet("Bob", "Hi")
greet("Charlie", "Hey", "?")
Output
Hello, Alice!
Hi, Bob!
Hey, Charlie?
How it works
Default parameter values are specified in the function definition using an equals sign. When a caller omits an argument for that parameter, Python uses the default value. This makes functions flexible and reduces code duplication. The function prints a formatted greeting using an f-string. The if __name__ == "__main__": guard ensures the demo code only runs when the script is executed directly, not when imported.
Common mistakes
- Using mutable defaults like `[]` or `{}` which are shared across calls
- Placing parameters without defaults after parameters with defaults, causing a SyntaxError
- Forgetting that default values are evaluated once at function definition time
Variations
- Return the string instead of printing it: `return f"{greeting}, {name}{punctuation}"`
- Use keyword arguments in calls: `greet(name="Alice", punctuation="!")`
Real-world use cases
- Logging functions that accept optional severity levels and formatting with default values.
- API client wrappers that set default timeouts or retry counts when not specified by the caller.
- Configuration loaders that default to common file paths or encoding when no override is provided.
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.