How to Parse Function Parameters with Defaults in Python
Create Python functions with default parameter values to make arguments optional and provide sensible fallbacks.
Python code
16 linesdef greet(name, greeting="Hello", punctuation="!"):
"""Greet a person with customizable greeting and punctuation."""
return f"{greeting}, {name}{punctuation}"
def describe_fruit(fruit, color="unknown", ripe=False):
"""Describe a fruit with optional attributes."""
status = "ripe" if ripe else "not ripe"
return f"{fruit} is {color} and {status}"
if __name__ == "__main__":
print(greet("Alice"))
print(greet("Bob", "Hi"))
print(greet("Charlie", "Hey", "!!!"))
print(describe_fruit("apple"))
print(describe_fruit("banana", "yellow", True))
print(describe_fruit("cherry", ripe=True))
Output
Hello, Alice!
Hi, Bob!
Hey, Charlie!!!
apple is unknown and not ripe
banana is yellow and ripe
cherry is unknown and ripe
How it works
Default parameters let you define values that are used when arguments are omitted. In greet, greeting and punctuation default to "Hello" and "!" respectively, so calling greet("Alice") uses those defaults. When you supply a value, like greet("Bob", "Hi"), it overrides the default. Using keyword arguments like ripe=True makes your code more readable and lets you skip earlier parameters. The __name__ == "__main__" guard ensures the test calls only run when the script is executed directly, not when imported.
Common mistakes
- Putting default parameters before non-default ones (syntax error)
- Using mutable defaults like lists or dicts, which are shared across calls
- Confusing keyword argument ordering with positional argument rules
Variations
- Use keyword-only arguments with `*` to force explicit naming
- Return a tuple instead of a string for more structured data
Real-world use cases
- Building CLI tools where optional flags set default behavior without extra code.
- API client functions that accept optional timeout or auth parameters with defaults.
- Configuration loaders that fall back to sensible values when keys are missing.
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.