This guide explains default parameters: usage and pitfalls through a focused Python example. You will learn the behavior to expect, why it matters in a real program, and how to recognize the common mistakes before applying it in your own project.
What You Will Learn
A default parameter is used when a caller omits that argument. Defaults are evaluated once at definition time, so they should normally be simple immutable values.
When and Why to Use It
The following example focuses on a practical use of Default Parameters: Usage and Pitfalls.
Step-by-Step Example
def calculate_shipping(subtotal, shipping_cost=5.0):
return subtotal + shipping_cost
print(calculate_shipping(40))
print(calculate_shipping(40, shipping_cost=0))
Understanding the Example
The first order uses the default shipping charge, producing 45. The second overrides it with zero, producing 40.
Expected Output
45.0
40
Important Behavior and Edge Cases
Do not hide a required input behind an arbitrary default, and avoid mutable default lists and dictionaries.
Try It Yourself
Add a discount percentage defaulting to zero to a price calculation function.
Common Beginner Mistakes
- Do not hide a required input behind an arbitrary default, and avoid mutable default lists and dictionaries.
- Confusing a returned value with printed output, or failing to verify a function’s behavior with different input values.
- Skipping the practice step and assuming the example covers every input. Test at least one normal case and one edge case relevant to this topic.
Key Takeaways
- A default parameter is used when a caller omits that argument.
- The first order uses the default shipping charge, producing 45.
- Apply the technique deliberately, checking its documented input requirements and failure behavior before integrating it into a larger project.