Data Science Python Functions
Put an analytical rule in a small function with an explicit contract.
How it works
A function gives a calculation a name and a defined input/output boundary. Prefer a function whose result depends on its arguments rather than hidden mutable state. Validate domain conditions that would make the result misleading. A per-hour measure needs positive opening hours; dividing by zero or quietly substituting one hour would conceal a data problem.
Run the code
Try in playground opens the correct python editor and preloads the complete source. Choose Run to execute; loading does not execute it. The isolated browser runtime does not read personal PC files.
Local review: Python 3.12.14, NumPy 2.5.4, Pandas 3.0.6 and SciPy 1.18.0. Browser review: Pyodide 0.27.7, Python 3.12.7, NumPy 2.0.2, Pandas 2.2.3 and SciPy 1.14.1 in their respective editors. Save the download as python-functions.py and run python python-functions.py in your separate environment. Apache and MySQL are not needed. Environment setup.
Example
import math
def litres_per_hour(litres, hours):
if not math.isfinite(litres) or not math.isfinite(hours) or litres < 0 or hours <= 0:
raise ValueError("nonnegative litres and positive finite hours required")
return litres / hours
assert litres_per_hour(21., 3.) == 7.
try:
litres_per_hour(21., 0.)
except ValueError:
print("Rate 7.0 L/hour; zero hours rejected")
else:
raise AssertionError("zero hours accepted")
Expected result
Rate 7.0 L/hour; zero hours rejected
The validation rejects invalid values before division. The example checks both a known rate and a boundary where no meaningful rate exists. A list of daily rates and a total-period rate answer different questions; the denominator policy must be part of the function’s documented purpose rather than guessed by its caller.
Technical references: NumPy, Pandas and SciPy. For evaluation design see the scikit-learn guide to leakage; these examples do not require scikit-learn.