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:
- Fluid Mechanics: Is the pipe flow laminar (\(\text{Re}_D < 2300\)), transitional (\(2300 \le \text{Re}_D \le 4000\)), or turbulent (\(\text{Re}_D > 4000\))? Picking the wrong correlation throws off your pump sizing by 400%!
- Heat Transfer (
Biot Number): Is \(\text{Bi} = h L_c / k < 0.1\)? If yes, simple lumped capacitance is valid; if no, you need spatial PDE series! - Thermodynamics (
Steam Phase): At pressure \(P\), is enthalpy \(h < h_f\) (compressed liquid), \(h_f \le h \le h_g\) (two-phase wet vapor), or \(h > h_g\) (superheated steam)?
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
- Order Matters in
if / elif / elif: Python picks ONLY the first branch whose condition isTrue, then skips the rest! Write strict thresholds cleanly (Re < 2300,elif Re <= 4000,else). - Never Compare Floats with Exact
==: Due to binary rounding (0.1 + 0.2), writeabs(energy_in - energy_out) < 1e-6when 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)
- What is the difference between writing two separate
ifstatements vs. oneif / elif / elsechain? - Why does
if grade == "steel" or "aluminum":ALWAYS evaluate toTrue? How must you write that test properly (grade == "steel" or grade == "aluminum"orgrade in ("steel", "aluminum"))? - When checking
delta_e = abs(E_in - E_out), why comparedelta_e < 1e-6instead ofE_in == E_out? - In nested checks (like quality
< 0.88inside two-phase steam), why must indentation match (4 spacesper 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!)
- 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'\), classifyingUNSAFE(\(n < 1.0\)),MARGINAL(\(1.0 \le n < 1.5\)),SAFE(\(n \ge 1.5\)). - 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\). - 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 faultpump_running = False), write a safety controller setting dump-valve state.