A function encapsulates a reusable block of logic. It takes parameters, performs a computation, and returns a result.
def kinetic_energy(mass, velocity):
# Compute KE = (1/2)mv^{2}
return 0.5 * mass * velocity**2
Why functions matter in physics
- Reusability: Write the formula once, call it for every data point.
- Readability:
kinetic_energy(m, v)is clearer than0.5 * m * v**2scattered throughout code. - Testability: You can verify each function independently.
Scope — Variables defined inside a function are local; they do not exist outside it.
def f(x):
result = x ** 2 # 'result' is local to f
return result
# print(result) → NameError!
Modular decomposition — Break a complex problem into smaller functions, each solving one sub-task:
main_simulation()
├── initialise_state()
├── compute_forces()
├── update_positions()
└── write_output()
Pure vs impure functions — A pure function depends only on its inputs and has no side effects. Pure functions are easier to test and debug.
Key insight: If you find yourself copy-pasting code, extract it into a function. The DRY principle (Don't Repeat Yourself) reduces bugs and simplifies maintenance.
Common pitfall: A function that prints a result and one that returns it look identical when run alone — but only the returner composes with other code. Printing is for humans; returning is for programs.