A function encapsulates a reusable block of logic, taking parameters, computing, and returning a result.
def kinetic_energy(mass, velocity):
return 0.5 * mass * velocity**2
- Reusability: Write once, call for any data point.
- Readability: Named calls beat raw math.
- Testability: Verify independently.
Scope: Variables defined inside are local and do not exist outside.
def f(x):
result = x ** 2
return result
# print(result) -> NameError!
Modular decomposition breaks complex problems into smaller functions solving single sub-tasks.
Purity and Pitfalls
| Function Type | Behavior | Testing | |
|---|---|---|---|
| Pure | Depends only on inputs, no side effects | Easy to test | |
| Impure | Modifies external state or relies on globals | Harder to test |
DRY Principle: Don't Repeat Yourself. If you copy-paste code, extract it into a function to reduce bugs and ease maintenance.
Common Pitfall: A function that prints versus one that returns. Printing is for humans to read, but only returning lets code compose functions together. Always return values for program use.