💻 Module: 02-Control-Flow • Unabridged Executed Lesson
📑 Download Module Slides (PDF) 🐍 Download Notebook (.ipynb)

Lesson 04: Decision Making in Engineering (if / elif / else)

The “Boring Stuff” Problem: Manual Engineering Decisions That Cannot Afford Mistakes

Every real engineering workflow is full of branch points:

Python’s conditional statements let you encode these engineering rules into airtight, automated inspection gates.


Comparison Operators, Boolean Logic & Chained Ranges

Operator Meaning Example Note
== Equal to material == "Al6061" Two equals signs compare; single = assigns!
!= Not equal status != "CAVITATING" Case-sensitive on strings
<, <=, >, >= Order tests 2300 <= Re_D <= 4000 Python allows chained comparisons just like math!
and, or, not Boolean gates (fos >= 1.5) and (defl_mm < limit_mm) Combine multiple safety criteria cleanly

Watch Out! Two Classic Conditional Bugs

  1. Order Matters in if / elif / elif: Python picks ONLY the first branch whose condition is True, then skips the rest! Write strict thresholds cleanly (Re < 2300, elif Re <= 4000, else).
  2. Never Compare Floats with Exact ==: Due to binary rounding (0.1 + 0.2), write abs(energy_in - energy_out) < 1e-6 when verifying conservation balances.
# Example 1 (Fluid Mechanics): Automated Pipe Flow & Suction Cavitation Inspector
rho = 998.2       # Water density at 20 degC [kg/m^3]
mu = 1.002e-3     # Dynamic viscosity [Pa*s]
D = 0.080         # Pipe diameter [m]
V = 2.4           # Bulk velocity [m/s]
NPSH_avail = 4.2  # Available Net Positive Suction Head [m]
NPSH_req = 4.6    # Manufacturer Required NPSH [m]

Re_D = (rho * V * D) / mu

if Re_D < 2300:
    regime = "Laminar (exact f = 64 / Re_D)"
elif 2300 <= Re_D <= 4000:
    regime = "Transitional (unstable — avoid operating here!)"
else:
    regime = "Turbulent (solve Colebrook-White / Haaland)"

# Combined Pump Safety Gate
if (NPSH_avail - NPSH_req) >= 0.5:
    pump_status = "PASS (safe >= 0.5 m cavitation margin)"
elif NPSH_avail >= NPSH_req:
    pump_status = "WARNING (borderline margin < 0.5 m)"
else:
    pump_status = "FAIL — CAVITATION DANGER (raise suction tank or slow pump!)"

print(f"Re_D = {Re_D:,.0f} -> {regime}")
print(f"NPSH Margin = {NPSH_avail - NPSH_req:+.2f} m -> {pump_status}")
Re_D = 191,272 -> Turbulent (solve Colebrook-White / Haaland)
NPSH Margin = -0.40 m -> FAIL — CAVITATION DANGER (raise suction tank or slow pump!)
# Example 2 (ME 200 Thermodynamics): Automated Saturated / Wet / Superheated Phase Classifier
# Cross-checking steam state at T = 150 degC using exact table bounds from Sat_Water_Temp
T_steam_c = 150.0
h_f, h_g = 632.18, 2746.4    # Saturated liquid & vapor enthalpy at 150 C [kJ/kg]
h_sample = 2150.0            # Measured turbine enthalpy [kJ/kg]

if h_sample < h_f:
    phase = "Compressed Liquid"
    quality = 0.0
elif h_sample <= h_g:
    quality = (h_sample - h_f) / (h_g - h_f)
    phase = f"Two-Phase Saturated Mixture (quality x = {quality:.4f})"
    if quality < 0.88:
        phase += " [WARNING: Turbine blade droplet erosion risk!]"
else:
    phase = "Superheated Vapor (quality undefined, x > 1)"

print(f"At T = {T_steam_c:.1f} C, h = {h_sample:.1f} kJ/kg -> {phase}")
At T = 150.0 C, h = 2150.0 kJ/kg -> Two-Phase Saturated Mixture (quality x = 0.7179) [WARNING: Turbine blade droplet erosion risk!]

Practice Questions (Concept Check)

  1. What is the difference between writing two separate if statements vs. one if / elif / else chain?
  2. Why does if grade == "steel" or "aluminum": ALWAYS evaluate to True? How must you write that test properly (grade == "steel" or grade == "aluminum" or grade in ("steel", "aluminum"))?
  3. When checking delta_e = abs(E_in - E_out), why compare delta_e < 1e-6 instead of E_in == E_out?
  4. In nested checks (like quality < 0.88 inside two-phase steam), why must indentation match (4 spaces per level)?

Guided Practice Problem 1 (Worked Self-Check): Biot Number & Lumped Capacitance Gate (Heat & Mass Transfer)

From Heat & Mass Transfer Module 2 (Steel_Quenching_Transient_Thermocouple_Dataset), a flat steel plate of half-thickness \(L_c = 25\text{ mm}\) (\(k = 45\text{ W/(m}\cdot\text{K)}\)) is quenched in oil with convection coefficient \(h = 420\text{ W/(m}^2\cdot\text{K)}\). Calculate \(\text{Bi} = h L_c / k\), and classify whether lumped capacitance applies (\(\text{Bi} < 0.1\)), one-term Heisler spatial approximation is needed (\(\text{Fo} > 0.2\) and \(\text{Bi} \ge 0.1\)), or multi-term series / numerical FDM is required.

Hint: Convert L_c = 25 mm to 0.025 m First!

Bi = h * L_c / k. Here 420 * 0.025 / 45 = 0.2333 >= 0.1, so lumped capacitance overpredicts cooling speed—we need spatial conduction!

# Worked Practice Problem 1 Solution: Quenching Model Selector
h_conv = 420.0   # W/(m^2*K)
k_steel = 45.0   # W/(m*K)
L_c = 0.025      # Half-thickness [m]
Fo = 0.35        # Fourier number alpha*t / L_c^2

Bi = (h_conv * L_c) / k_steel
if Bi < 0.1:
    model = "Lumped Capacitance valid (< 5% spatial temperature gradient)"
elif Fo > 0.2:
    model = "Biot >= 0.1 and Fo > 0.2 -> Use Spatial 1-Term Heisler Approximation"
else:
    model = "Biot >= 0.1 and Early Time (Fo <= 0.2) -> Full Eigenseries or Numerical FDM required"

print(f"Bi = {Bi:.4f}, Fo = {Fo:.2f} -> {model}")
Bi = 0.2333, Fo = 0.35 -> Biot >= 0.1 and Fo > 0.2 -> Use Spatial 1-Term Heisler Approximation

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

  1. Combined Tension & Torsion Yield Check (Solid Mechanics): Given normal stress \(\sigma_x = 140\text{ MPa}\), shear stress \(\tau_{xy} = 85\text{ MPa}\), and steel yield \(S_y = 290\text{ MPa}\), compute von Mises equivalent stress \(\sigma' = \sqrt{\sigma_x^2 + 3\tau_{xy}^2}\) and safety factor \(n = S_y / \sigma'\), classifying UNSAFE (\(n < 1.0\)), MARGINAL (\(1.0 \le n < 1.5\)), SAFE (\(n \ge 1.5\)).
  2. Normal Shock Mach Checker (Fluid Mechanics Module 7): Given upstream velocity \(V_1 = 580\text{ m/s}\) and air temperature \(T_1 = 240\text{ K}\) (\(\gamma = 1.4, R = 287\text{ J/(kg}\cdot\text{K)}\)), compute \(Ma_1 = V_1 / \sqrt{\gamma R T_1}\) and print whether a normal shock is physically impossible (\(Ma_1 \le 1\), Second Law \(\Delta s \ge 0\)) or evaluate post-shock Mach number \(Ma_2\).
  3. Solar Thermal Stagnation Guard (Solar Thermal): Given \(T_{\text{tank}} = 94^\circ\text{C}\) and boiler limit \(95^\circ\text{C}\) (with glycol loop pump fault pump_running = False), write a safety controller setting dump-valve state.

🎬 Concept & Engineering Animation

🎬 Reynolds Flow Gate