How to Create Functions with Default Parameters in Python
This code defines two Python functions using default parameters to handle missing arguments gracefully, demonstrating how to work with optional inputs and keyword arguments.
Python code
28 linesdef greet(name="Guest", greeting="Hello", punctuation="!"):
"""Generate a greeting message using default parameters."""
return f"{greeting}, {name}{punctuation}"
def create_profile(username="anonymous", age=0, city="Unknown", active=True):
"""Create a user profile dictionary with default values."""
return {
"username": username,
"age": age,
"city": city,
"active": active,
}
if __name__ == "__main__":
# Using default parameters
print(greet()) # "Hello, Guest!"
print(greet("Alice")) # "Hello, Alice!"
print(greet("Bob", "Hi")) # "Hi, Bob!"
print(greet("Sam", "Hey", "?")) # "Hey, Sam?"
# Using keyword arguments to skip defaults
print(greet(punctuation="!!!")) # "Hello, Guest!!!"
# Dictionary example
print(create_profile()) # Default profile
print(create_profile("john_doe", 25, "NYC")) # Partial defaults
Output
Hello, Guest!
Hello, Alice!
Hi, Bob!
Hey, Sam?
Hello, Guest!!!
{'username': 'anonymous', 'age': 0, 'city': 'Unknown', 'active': True}
{'username': 'john_doe', 'age': 25, 'city': 'NYC', 'active': True}
How it works
Default parameters let a function use a fallback value when an argument is omitted, making the function flexible and easier to call. The defaults are evaluated once at function definition time, so they work well with immutable types like strings and ints. Using keyword arguments like punctuation='!!!' lets you skip earlier parameters and override only the one you need. The create_profile function shows how defaults help build configuration-like dictionaries without requiring every field.
Common mistakes
- Using mutable defaults like `def f(x=[])` can cause shared-state bugs.
- Default parameters are evaluated at definition time, so don't rely on runtime values.
- Forgetting that positional arguments must be passed in order if you don't use keywords.
- Placing a parameter without a default before one with a default is a syntax error.
Variations
- Use `*args` and `**kwargs` to accept an arbitrary number of arguments.
- Use `functools.partial` to fix arguments ahead of time and create callable presets.
Real-world use cases
- Building API client constructors that use sane defaults for host, timeout, and retries.
- Creating configuration objects where most fields have default values but can be overridden by user settings.
- Writing CLI helper functions that provide sensible defaults for flags like verbose or color.
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.