How to use function defaults in Python
Define Python functions with default parameter values so callers can omit arguments and use sensible fallbacks.
Python code
29 linesdef greet(name="Guest", greeting="Hello", punctuation="!"):
"""Return a greeting message using default parameters."""
return f"{greeting}, {name}{punctuation}"
def describe_pet(pet_name, animal_type="dog"):
"""Display information about a pet with a default animal type."""
print(f"I have a {animal_type} named {pet_name}.")
def multiply(x, y=2, z=3):
"""Multiply numbers, using defaults for missing arguments."""
return x * y * z
if __name__ == "__main__":
# Using defaults for all parameters
print(greet())
# Overriding some defaults
print(greet("Alice"))
print(greet("Bob", "Hi"))
print(greet("Charlie", "Hey", "."))
# Demonstrating a function with a default parameter
describe_pet("Rex")
describe_pet("Whiskers", "cat")
# Function with multiple defaults
print(multiply(5)) # 5 * 2 * 3 = 30
print(multiply(5, 4)) # 5 * 4 * 3 = 60
print(multiply(5, 4, 2)) # 5 * 4 * 2 = 40
Output
Hello, Guest!
Hello, Alice!
Hi, Bob!
Hey, Charlie.
I have a dog named Rex.
I have a cat named Whiskers.
30
60
40
How it works
Default parameters in Python let you set fallback values for arguments that are not passed. When a caller omits an argument, Python automatically uses the default value defined in the function signature. This example shows how defaults work for strings, printing, and multiple numeric arguments. Defaults are evaluated once when the function is defined, so use immutable types like strings or numbers for safety.
Common mistakes
- Putting parameters with defaults before parameters without defaults (SyntaxError)
- Using mutable defaults like lists or dicts that persist across calls
- Forgetting that defaults are evaluated once at definition time
Variations
- Use keyword-only arguments with `*` before default parameters to force explicit naming.
- Use `None` as the default and assign a fresh mutable object inside the function.
Real-world use cases
- Building a configurable HTTP client where timeout and retries have sensible defaults.
- Writing logging helpers that default to DEBUG but accept a custom level.
- Creating CLI tools where optional flags default to safe values.
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.