A community workshop cuts ribbon to mark sections of a display. Each section needs the same length. If we know the section count and length, a function is enough to calculate the total:
def ribbon_needed(section_count, length_per_section):
return section_count * length_per_section
print(ribbon_needed(3, 4))
print(ribbon_needed(5, 4))
Output:
12
20
The first call supplies 3 and 4; the function returns 12. The second supplies different values and uses the same rule. The function does not remember either result. The unit is whatever consistent length unit the inputs use; this example assumes nonnegative whole numbers.
A descriptive name makes the calculation easier to find and check. Giving a shared rule one home also means a correction starts in one place. This is the idea behind Don’t Repeat Yourself (DRY): avoid maintaining the same knowledge separately. Two expressions that happen to look alike may represent different rules, however, and may need to change independently.
Changing code’s organization while preserving its intended observable behavior is called refactoring. Compare results and check assumptions; moving an incorrect calculation does not correct it. Clear structure helps people inspect code but does not prove correctness or improve speed by itself.
Python values are objects already, but writing a new class is optional. When a result can be calculated from inputs and nothing needs to be remembered, a function is often the clearer choice.