💻 Module: 03-Functions-Modules • Unabridged Executed Lesson
📑 Download Module Slides (PDF) 🐍 Download Notebook (.ipynb)

Lesson 07: Defining Functions (def) — Build Your Own Engineering Toolbox

The “Boring Stuff” Problem: Copy-Pasting the Same 10-Line Equation Everywhere

Suppose you are analyzing a shell-and-tube heat exchanger (Heat & Mass Transfer Module 5) at six operating points, and each operating point has two fluid streams whose Reynolds numbers, Darcy friction factors, and Log-Mean Temperature Differences (LMTD) must be computed cleanly. If you copy-paste those equations 12 times and later catch a unit mistake in one term, you have to hunt down all 12 copies!

Functions solve this once and for all. Think of a Python function (def) like a calibrated black-box bench instrument:

  1. You feed raw measurements into its input ports (parameters),
  2. The internal wiring runs cleanly inside a sealed local workspace (scope),
  3. And it hands back exact, reusable outputs via return (NOT print!).

Beginners often write print(result) inside a function instead of return result. Here is why that breaks engineering workflows:

Watch Out! Local vs. Global Scope Trap

Variables created inside a function are local—they live inside that function and vanish when return finishes. Never rely on hidden global variables inside a calculation function (e.g., assuming g = 9.81 sits outside unless it is passed as a parameter or clearly defined as a CONSTANT).

import math

# Example 1 (Fluid Mechanics Module 5): Reusable Pipe Flow Analyzer Returning Multiple Values
def solve_colebrook(Re_D: float, eps_D: float, tol: float = 1e-10) -> float:
    '''Return Darcy friction factor f for laminar or turbulent circular pipe flow.'''
    if Re_D <= 0:
        raise ValueError("Reynolds number Re_D must be positive.")
    if Re_D < 2300.0:
        return 64.0 / Re_D
    f = (-1.8 * math.log10((eps_D / 3.7) ** 1.11 + 6.9 / Re_D)) ** -2
    for _ in range(40):
        f_new = 1.0 / (-2.0 * math.log10(eps_D / 3.7 + 2.51 / (Re_D * math.sqrt(f)))) ** 2
        if abs(f_new - f) < tol:
            return f_new
        f = f_new
    return f


def pipe_head_and_power(Q_m3s, D_m, L_m, eps_m=4.5e-5, rho=998.0, mu=1.002e-3, eta_pump=0.78):
    '''Return (velocity_m_s, Re_D, f_darcy, h_f_m, shaft_power_kW) for a pipe run.'''
    area = math.pi * (D_m ** 2) / 4.0
    V = Q_m3s / area
    Re_D = rho * V * D_m / mu
    f = solve_colebrook(Re_D, eps_m / D_m)
    h_f = f * (L_m / D_m) * (V ** 2 / (2.0 * 9.80665))
    shaft_kw = (rho * 9.80665 * Q_m3s * h_f / eta_pump) / 1000.0
    return V, Re_D, f, h_f, shaft_kw   # Returning a tuple lets callers unpack cleanly!


# Call our toolbox cleanly on 3 pipe flows in 4 lines!
print("Flow [L/s] | V [m/s] |   Re_D    |   f    | h_f [m] | Pump [kW]")
print("-" * 64)
for Q_L_s in [8.0, 15.0, 24.0]:
    V, Re, f, hf, kw = pipe_head_and_power(Q_L_s / 1000.0, D_m=0.10, L_m=180.0)
    print(f"{Q_L_s:10.1f} | {V:7.2f} | {Re:9,.0f} | {f:6.4f} | {hf:7.2f} | {kw:9.3f}")
Flow [L/s] | V [m/s] |   Re_D    |   f    | h_f [m] | Pump [kW]
----------------------------------------------------------------
       8.0 |    1.02 |   101,453 | 0.0201 |    1.91 |     0.192
      15.0 |    1.91 |   190,224 | 0.0187 |    6.24 |     1.175
      24.0 |    3.06 |   304,358 | 0.0179 |   15.34 |     4.620
# Example 2 (Heat & Mass Transfer Module 5): Counterflow vs Parallel-Flow LMTD Helper
def calc_lmtd(T_h_in, T_h_out, T_c_in, T_c_out, mode="counterflow"):
    '''Compute Log-Mean Temperature Difference [K or degC] with Pinch Guard.'''
    if mode == "counterflow":
        dT1 = T_h_in - T_c_out
        dT2 = T_h_out - T_c_in
    elif mode == "parallel":
        dT1 = T_h_in - T_c_in
        dT2 = T_h_out - T_c_out
    else:
        raise ValueError(f"Unknown flow mode: {mode}")

    if dT1 <= 0 or dT2 <= 0:
        raise ValueError("Second-Law temperature cross! Terminal dT <= 0.")
    if abs(dT1 - dT2) < 1e-6:   # Exact equal-dT limit prevents 0 / ln(1) ZeroDivisionError!
        return dT1
    return (dT1 - dT2) / math.log(dT1 / dT2)


for flow_type in ["counterflow", "parallel"]:
    lmtd = calc_lmtd(T_h_in=140.0, T_h_out=75.0, T_c_in=25.0, T_c_out=60.0, mode=flow_type)
    print(f"{flow_type.capitalize():12s} LMTD = {lmtd:.2f} K")
Counterflow  LMTD = 63.83 K
Parallel     LMTD = 49.09 K

Notice that subtle engineering touch inside calc_lmtd: when dT1 == dT2, (dT1 - dT2) / ln(dT1 / dT2) divides 0.0 / 0.0! Good engineering functions check those edge cases (abs(dT1 - dT2) < 1e-6) explicitly using L’Hopital’s limit return dT1.


Practice Questions (Concept Check)

  1. What does a function return by default if you reach the bottom of its code block without a return statement?
  2. Why did calc_lmtd handle abs(dT1 - dT2) < 1e-6 with an early return dT1?
  3. How do you unpack two values returned by return stress_mpa, fos?
  4. True or False: Putting a '''Docstring''' right under def func(): lets help(func) display usage instructions automatically.

Guided Practice Problem 1 (Worked Self-Check): Non-Ideal Turbine Stage Function (ME 200 & ME 300)

Write a clean function turbine_expansion(T3_k, P3_bar, P4_bar, eta_turb=0.88, k=1.4, cp=1.005) that computes and returns (T4_actual_k, T4_isen_k, w_actual_kj_kg) for air expanding through a gas turbine stage using \(T_{4s} = T_3 (P_4/P_3)^{(k-1)/k}\) and \(T_4 = T_3 - \eta_t (T_3 - T_{4s})\). Test it on T3 = 1480 K, P3 = 16 bar, P4 = 1.05 bar.

Hint: Isentropic efficiency reduces work extracted, so T4_actual > T4_isen

Check your physics: actual exhaust temperature \(T_4\) MUST be hotter than \(T_{4s}\) because irreversibility keeps enthalpy in the exhaust!

# Worked Practice Problem 1 Solution: Turbine Expansion Function
def turbine_expansion(T3_k, P3_bar, P4_bar, eta_turb=0.88, k=1.4, cp=1.005):
    '''Return (T4_actual_K, T4_isen_K, w_actual_kJ_kg) for gas turbine expansion.'''
    T4s = T3_k * (P4_bar / P3_bar) ** ((k - 1.0) / k)
    T4 = T3_k - eta_turb * (T3_k - T4s)
    w_actual = cp * (T3_k - T4)
    return T4, T4s, w_actual

t4, t4s, w_t = turbine_expansion(1480.0, 16.0, 1.05, eta_turb=0.88)
print(f"T4s = {t4s:.1f} K | T4_actual = {t4:.1f} K | Turbine Work = {w_t:.2f} kJ/kg")
T4s = 679.6 K | T4_actual = 775.7 K | Turbine Work = 707.83 kJ/kg

End-of-Chapter Practice Problems (Try Yourself!)

  1. Rectangular Beam Section Calculator (Solids & Calc I): Write rect_beam_props(b_m, h_m) returning (area_m2, I_xx_m4, section_modulus_Z_m3) where \(Z = I_{xx} / (h/2)\). Use it to size which beam (40x80 mm, 50x100 mm, 60x120 mm) keeps bending stress under 120 MPa for moment M = 4.5 kN*m.
  2. External Cylinder Cross-Flow Nusselt Number (Heat Transfer): Write a function implementing Churchill–Bernstein correlation for a cylinder in air crossflow (Re_D, Pr=0.71), returning Nu_D and heat transfer coefficient h = Nu_D * k / D.
  3. Temperature Converter Utility with Validation: Write to_kelvin(val, unit="C") accepting "C", "F", or "K" (case-insensitive!) and raising a clear ValueError if an unphysical temperature below absolute zero (< 0 K) is entered.

🎬 Concept & Engineering Animation

🎬 Function Black Box Scope