How to Use Default Parameters in Python Functions
A beginner-friendly Python function that uses default parameters to compare two numbers with equal, greater, or less operations.
Python code
15 linesdef compare(a, b, operation="equal"):
if operation == "equal":
return a == b
elif operation == "greater":
return a > b
elif operation == "less":
return a < b
else:
return f"Unknown operation: {operation}"
if __name__ == "__main__":
print(compare(5, 5))
print(compare(5, 3, "greater"))
print(compare(5, 3, "less"))
print(compare(5, 3, "different"))
Output
True
True
False
Unknown operation: different
How it works
The operation parameter defaults to "equal", so calling compare(5, 5) skips the operation argument and compares for equality. The if/elif chain returns a boolean for each supported operation, or a descriptive string when the operation is unrecognized. Default parameters let you create flexible functions that still work with minimal arguments. The __main__ guard ensures the demo runs only when the script is executed directly, not when imported.
Common mistakes
- Forgetting to pass a default value when the parameter has a default — this leads to a TypeError about missing arguments.
- Default parameters are evaluated once at definition time, not each call — avoid mutable defaults like `[]` or `{}` here.
Variations
- Use a match statement instead of if/elif for more readable operation handling in Python 3.10+.
- Return a custom error with `raise ValueError` for unknown operations instead of a string.
Real-world use cases
- Building a CLI tool where a sorting flag defaults to ascending order unless specified.
- Implementing a config parser that assumes a default JSON format but allows overrides.
- Writing a validation function that checks equality by default but can switch to greater-than for range checks.
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.