This guide explains when to extract repeated code into a function 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
Extract a function when a repeatable piece of logic has a meaningful name, clear inputs and a useful result. Avoid creating functions for every individual statement: the purpose is clearer structure and reusable behavior.
When and Why to Use It
The following example focuses on a practical use of When to Extract Repeated Code into a Function.
Step-by-Step Example
def calculate_discount(price, discount_rate):
return price * (1 - discount_rate)
print(calculate_discount(80, 0.10))
print(calculate_discount(50, 0.20))
Understanding the Example
Both calls use one implementation, preventing duplicated calculation rules. The function name describes the business operation rather than the individual multiplication.
Expected Output
72.0
40.0
Important Behavior and Edge Cases
A long function with unrelated responsibilities is hard to test, but splitting tiny expressions into countless helpers can also reduce readability.
Try It Yourself
Find a repeated tax calculation in a practice script and move it into one descriptive function.
Common Beginner Mistakes
- A long function with unrelated responsibilities is hard to test, but splitting tiny expressions into countless helpers can also reduce readability.
- 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
- Extract a function when a repeatable piece of logic has a meaningful name, clear inputs and a useful result.
- Both calls use one implementation, preventing duplicated calculation rules.
- Apply the technique deliberately, checking its documented input requirements and failure behavior before integrating it into a larger project.