Lesson
10: Defining Engineering Functions (def) —
print vs. return & Isolated Scope
The “Boring Stuff” Problem: Copy-Pasting River Mixing or Settling Formulas 12 Times
Imagine sizing a municipal drinking-water grit chamber and sedimentation basin across 8 particle grain diameters—or calculating downstream BOD/nitrate concentrations below 6 tributaries. If you copy-paste the Stokes settling formula 8 times and later update water viscosity at \(10^\circ\text{C}\), you have to track down and fix all 8 copies!
Think of a Python function (def) as a sealed, calibrated
laboratory analyzer:
- Inputs (Parameters): You feed river flows, diameters, or temperatures through clearly named ports.
- Isolated Scope: Temporary variables created inside the function stay private inside the box—no accidental overwriting of outer script variables!
returnOutputs (NOTprint()): Returning values (return C_mix, Q_tot) lets downstream loops, optimizers, and plotting scripts reuse the answers automatically!
Watch Out!
print(result) Returns None
Never end a physics helper with print(vs) instead of
return vs. Printing puts text on your screen for human eyes
and throws the number away
(TypeError: unsupported operand type(s) for *: 'float' and 'NoneType'!).
from pathlib import Path
def data_file(name):
"""Locate a dataset file whether running from SRC_DIR, module folder, HOMEWORK, or EXAMS."""
for p in [
Path("datasets") / name,
Path("../datasets") / name,
Path("../../datasets") / name,
]:
if p.exists():
return p
raise FileNotFoundError(f"Missing dataset {name} in datasets/")
import math
# Example 1 (Water Quality & Rivers): Point-Source River Mixing Dilution Calculator
def river_mixing(Q_river_m3s: float, C_river_mgL: float, Q_waste_m3s: float, C_waste_mgL: float) -> tuple[float, float]:
'''Return (Q_total_m3s, C_mixed_mgL) assuming instantaneous complete mixing.'''
if Q_river_m3s < 0 or Q_waste_m3s < 0:
raise ValueError("Volumetric flow rates cannot be negative.")
q_total = Q_river_m3s + Q_waste_m3s
if q_total == 0.0:
raise ValueError("Total flow rate must exceed zero.")
c_mix = (Q_river_m3s * C_river_mgL + Q_waste_m3s * C_waste_mgL) / q_total
return q_total, c_mix
print("Season | Q_river [m^3/s] | Q_total [m^3/s] | Mixed NO3 [mg/L]")
print("-" * 68)
for season, q_riv, c_riv in [("Spring Wet", 42.0, 1.8), ("Summer Avg", 14.5, 2.2), ("Sept Drought", 3.8, 2.6)]:
qt, cmix = river_mixing(q_riv, c_riv, Q_waste_m3s=0.85, C_waste_mgL=28.0)
print(f"{season:<11s} | {q_riv:15.2f} | {qt:15.2f} | {cmix:16.2f}")Season | Q_river [m^3/s] | Q_total [m^3/s] | Mixed NO3 [mg/L]
--------------------------------------------------------------------
Spring Wet | 42.00 | 42.85 | 2.32
Summer Avg | 14.50 | 15.35 | 3.63
Sept Drought | 3.80 | 4.65 | 7.24
# Example 2 (Water Treatment & Fluid Mechanics Course): Temperature-Aware Stokes Settling Velocity
# Cross-reference: Fluids_Water_Properties_Table.csv (Fluid Mechanics Module 1 viscosity mu(T))
def lookup_water_props(temp_c: float) -> tuple[float, float]:
'''Look up exact (rho_w [kg/m^3], mu_w [Pa*s]) from Fluids_Water_Properties_Table.csv.'''
rows = data_file("Fluids_Water_Properties_Table.csv").read_text(encoding="utf-8").splitlines()[1:]
best = None
best_diff = 1e9
for row in rows:
cols = [float(x) for x in row.split(",")]
if abs(cols[0] - temp_c) < best_diff:
best_diff = abs(cols[0] - temp_c)
best = (cols[2], cols[3])
return best
def stokes_settling_velocity(d_mm: float, rho_particle: float = 2650.0, temp_c: float = 20.0) -> tuple[float, float]:
'''Return (settling_vel_m_s, particle_Re) using Stokes law & real Fluid Mechanics viscosity.'''
rho_w, mu_w = lookup_water_props(temp_c)
d_m = d_mm * 1e-3
g = 9.80665
vs = g * (rho_particle - rho_w) * (d_m ** 2) / (18.0 * mu_w)
rep = rho_w * vs * d_m / mu_w
return vs, rep
print("Temp [C] | d_p [mm] | v_s [mm/s] | Particle Re_p | Stokes Valid (Re_p < 1)?")
print("-" * 74)
for tc in [5.0, 20.0]:
for dmm in [0.02, 0.08, 0.15]:
vs, rep = stokes_settling_velocity(dmm, rho_particle=2650.0, temp_c=tc)
print(f"{tc:8.0f} | {dmm:8.2f} | {vs*1000:10.3f} | {rep:13.3f} | {'Yes' if rep < 1.0 else 'Transition (>1)'}")Temp [C] | d_p [mm] | v_s [mm/s] | Particle Re_p | Stokes Valid (Re_p < 1)?
--------------------------------------------------------------------------
5 | 0.02 | 0.201 | 0.002 | Yes
5 | 0.08 | 3.211 | 0.143 | Yes
5 | 0.15 | 11.288 | 0.945 | Yes
20 | 0.02 | 0.359 | 0.007 | Yes
20 | 0.08 | 5.748 | 0.458 | Yes
20 | 0.15 | 20.208 | 3.020 | Transition (>1)
Look at what our clean functions revealed automatically: dropping
river water temperature from \(20^\circ\text{C}\) to \(5^\circ\text{C}\) doubles dynamic viscosity
(mu_w rises!) and cuts particle settling speed
dramatically—that is why cold-winter drinking-water sedimentation basins
perform worse unless engineered for winter viscosity!
Concept Check Questions
- Explain what happens if
river_mixingends withprint(c_mix)and omitsreturn q_total, c_mix. - What does tuple unpacking
qt, cmix = river_mixing(...)require on the left-hand side? - Why did
stokes_settling_velocityconvertd_mm * 1e-3inside the function while keeping the input port user-friendly in millimeters?
Guided
Practice Problem 1: Clarifier Surface Overflow Rate (SOR)
Function
Write a function
clarifier_removal_check(Q_m3d: float, diameter_m: float, vs_m_s: float)
that computes basin surface area \(A = \pi D^2
/ 4\), Surface Overflow Rate \(\text{SOR} = Q_{\text{m}^3/\text{s}} / A\)
(\(\text{m/s}\) and \(\text{m/day}\)), and particle fractional
removal min(1.0, vs_m_s / SOR). Test on a \(28\text{ m}\) diameter primary clarifier
treating \(15,000\text{
m}^3/\text{day}\) with silt settling velocity
0.60 mm/s.
# Guided Practice 1 Starter
def clarifier_removal_check(Q_m3d: float, diameter_m: float, vs_m_s: float) -> tuple[float, float]:
area = math.pi * (diameter_m ** 2) / 4.0
sor_m_s = (Q_m3d / 86400.0) / area
frac = min(1.0, vs_m_s / sor_m_s)
return sor_m_s * 86400.0, frac * 100.0
sor_md, pct = clarifier_removal_check(15000.0, 28.0, 0.00060)
print(f"Clarifier SOR = {sor_md:.2f} m/day -> Ideal Overflow Removal = {pct:.1f}%")Clarifier SOR = 24.36 m/day -> Ideal Overflow Removal = 100.0%