How to Use Default Parameters in Python Functions
Create a simple function with default parameters to build flexible, reusable greetings in Python.
Python code
10 linesdef greet(name, greeting="Hello", punctuation="!"):
"""Return a personalized greeting message."""
return f"{greeting}, {name}{punctuation}"
if __name__ == "__main__":
print(greet("Alice"))
print(greet("Bob", "Hi"))
print(greet("Charlie", greeting="Hey", punctuation="?"))
print(greet("Dana", punctuation="..."))
Output
Hello, Alice!
Hi, Bob!
Hey, Charlie?
Hello, Dana...
How it works
The greet function defines three parameters: name, greeting, and punctuation, with the last two having default values. When a caller omits an argument for these, Python automatically uses the default, making the function flexible without extra logic. Using keyword arguments like greeting="Hey" improves readability and allows you to skip earlier parameters. The if __name__ == "__main__": guard ensures the test calls run only when the script is executed directly, not when imported.
Common mistakes
- Placing a parameter with a default before a parameter without one, which raises a SyntaxError.
- Using mutable default values like lists or dicts, which are shared across calls and can cause bugs.
- Forgetting that default values are evaluated once at function definition time, so dynamic defaults need a sentinel like None.
Variations
- Use `def greet(name, greeting='Hello', punctuation='!', /)` to make parameters positional-only.
- Call with all arguments positionally: `greet('Alice', 'Hi', '?')`.
Real-world use cases
- Customizing log messages with optional severity levels or prefixes in a logging utility.
- Building a configuration loader with optional environment-based overrides and defaults.
- Creating API client methods where optional query parameters have sensible defaults.
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.