Lesson 05: for Loops & Automating Parametric Design Sweeps

The “Boring Stuff” Problem: Sweeping Diameters, Pressure Ratios, and Fin Lengths

Nobody designs a pipe, gas turbine, or heat-sink fin for one single value. Your boss asks: “Show me how pump power changes as we step pipe diameter from 50 mm up to 200 mm,” or “Find which Brayton pressure ratio gives maximum specific net work.”

Copying and pasting formulas 15 times is how spreadsheets become unmaintainable nightmares. A for loop runs the exact same block of code automatically for every single item in a sequence (range(), list, tuple, or paired lists via zip()).


How for Loops Work + Three Essential Helpers (range, enumerate, zip)

Watch Out! Two Classic Loop Traps

  1. Accumulator Inside the Loop: Putting total_heat = 0.0 inside the for body resets your sum back to zero on every iteration! Accumulator initialization MUST happen above the for line.
  2. Off-by-One Stopping: range(10, 50, 10) stops at 40, NOT 50. To include 50, write range(10, 51, 10).
# Example 1 (ME 300 Gas Power Cycles): Brayton Pressure-Ratio Parametric Sweep
# Compares Thermal Efficiency eta_th vs. Net Specific Work w_net (fixed T1 = 300 K, T3 = 1450 K)
T1 = 300.0     # Compressor inlet [K]
T3 = 1450.0    # Turbine inlet metallurgical limit [K]
cp = 1.005     # Air cp [kJ/(kg*K)]
k = 1.4

best_rp, max_work = None, -1.0
print(f"{'r_p':>5} | {'T2 [K]':>8} | {'T4 [K]':>8} | {'eta_th':>8} | {'w_net [kJ/kg]':>13}")
print("-" * 54)

for rp in range(4, 29, 4):
    exp_factor = rp ** ((k - 1.0) / k)
    T2 = T1 * exp_factor
    T4 = T3 / exp_factor
    w_comp = cp * (T2 - T1)
    w_turb = cp * (T3 - T4)
    w_net = w_turb - w_comp
    eta = 1.0 - 1.0 / exp_factor
    print(f"{rp:5d} | {T2:8.1f} | {T4:8.1f} | {eta:8.2%} | {w_net:13.2f}")
    if w_net > max_work:
        max_work, best_rp = w_net, rp

print(f"\n-> Optimum specific net work = {max_work:.2f} kJ/kg at r_p = {best_rp}!")
print(f"   (Analytical check: r_p,opt = (T3/T1)^(k/(2*(k-1))) = {(T3/T1)**(k/(2*(k-1))):.2f})")
r_p |   T2 [K] |   T4 [K] |   eta_th | w_net [kJ/kg]
------------------------------------------------------
    4 |    445.8 |    975.8 |   32.70% |        330.07
    8 |    543.4 |    800.5 |   44.80% |        408.13
   12 |    610.2 |    712.9 |   50.83% |        429.05
   16 |    662.5 |    656.6 |   54.71% |        433.05
   20 |    706.1 |    616.1 |   57.51% |        429.98
   24 |    743.8 |    584.8 |   59.67% |        423.47
   28 |    777.3 |    559.6 |   61.41% |        415.13

-> Optimum specific net work = 433.05 kJ/kg at r_p = 16!
   (Analytical check: r_p,opt = (T3/T1)^(k/(2*(k-1))) = 15.76)
# Example 2 (Heat Transfer + Pin Fin Data): Accumulating Total Cooling Over Real Air Velocities
import math

# Rectangular aluminum cooling fins (N = 16 fins, k = 180 W/mK, L = 30 mm, t = 2 mm, W = 50 mm)
N_fins, k_al, L, t, W = 16, 180.0, 0.030, 0.002, 0.050
P = 2.0 * (W + t)
Ac = W * t
theta_b = 55.0  # Base excess temperature (T_b - T_inf) [K]

velocities = [1.5, 3.0, 5.0, 8.0]
h_values = [28.0, 44.5, 62.0, 84.0]  # W/(m^2*K) from wind-tunnel correlation

print("Air Vel [m/s] | h [W/m2K] | Fin Eff eta_f | Total Heat 16 Fins [W]")
print("-" * 64)
for v, h in zip(velocities, h_values):
    m = math.sqrt((h * P) / (k_al * Ac))
    eta_f = math.tanh(m * L) / (m * L)
    q_single = eta_f * h * (P * L) * theta_b
    q_total = N_fins * q_single
    print(f"{v:13.1f} | {h:9.1f} | {eta_f:13.2%} | {q_total:21.2f}")
Air Vel [m/s] | h [W/m2K] | Fin Eff eta_f | Total Heat 16 Fins [W]
----------------------------------------------------------------
          1.5 |      28.0 |        95.41% |                 73.35
          3.0 |      44.5 |        92.94% |                113.55
          5.0 |      62.0 |        90.48% |                154.02
          8.0 |      84.0 |        87.60% |                202.04

Practice Questions (Concept Check)

  1. What numbers does list(range(2, 10, 3)) produce?
  2. Why use zip(temps, enthalpies) instead of indexing with for i in range(len(temps)) when walking parallel lists?
  3. What does continue do inside a loop vs. break?
  4. When finding a maximum inside a loop, why is initializing best_val = values[0] (or -float("inf")) safer than best_val = 0.0?

Guided Practice Problem 1 (Worked Self-Check): Solar Collector Hourly Thermal Energy Accumulator (Solar Thermal)

Using datasets/Solar_Collector_FlatPlate_Hourly_Data.csv, iterate through the 24 hourly collector records (hour, G_T_W_m2, efficiency_percent), skip nighttime hours (G_T_W_m2 <= 0), compute useful power \(q_u = A_c G_T (\eta / 100)\) for an \(A_c = 4.0\text{ m}^2\) solar thermal array, and accumulate total daily thermal energy harvested in kWh.

Hint: 1 W for 1 hour = 0.001 kWh

Check if G_T <= 0: continue, accumulate energy_wh += q_u, then divide energy_wh / 1000.0 after the loop!

# Worked Practice Problem 1 Solution: Daily Solar Collector Energy Integration
from pathlib import Path

solar_path = next(
    p for p in [
        Path("datasets/Solar_Collector_FlatPlate_Hourly_Data.csv"),
        Path("../datasets/Solar_Collector_FlatPlate_Hourly_Data.csv"),
    ] if p.exists()
)

A_c = 4.0       # m^2 collector array
total_wh = 0.0
peak_q_w = 0.0
peak_hr = 0

lines = solar_path.read_text(encoding="utf-8").splitlines()[1:]
for line in lines:
    hr_s, gt_s, tamb_s, ul_s, eff_s = line.split(",")
    hr, gt, eff_pct = int(float(hr_s)), float(gt_s), float(eff_s)
    if gt <= 0.0:
        continue
    q_u_w = A_c * gt * (eff_pct / 100.0)
    total_wh += q_u_w * 1.0  # 1-hour step -> Wh
    if q_u_w > peak_q_w:
        peak_q_w, peak_hr = q_u_w, hr

print(f"Active Daylight Array (A_c = {A_c} m^2)")
print(f"Peak Output : {peak_q_w:.1f} W at Hour {peak_hr:02d}:00")
print(f"Daily Yield : {total_wh / 1000.0:.3f} kWh/day ({total_wh * 3.6 / 1000.0:.2f} MJ/day)")
Active Daylight Array (A_c = 4.0 m^2)
Peak Output : 2383.2 W at Hour 12:00
Daily Yield : 18.203 kWh/day (65.53 MJ/day)

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

  1. Riemann Work Integration (ME 200): Approximate polytropic piston-cylinder compression work \(W = \int_{V_1}^{V_2} P\,dV\) (\(P V^{1.3} = C\), \(V_1 = 0.40\text{ m}^3\), \(P_1 = 120\text{ kPa}\), \(V_2 = 0.08\text{ m}^3\)) using a for loop with \(N = 100\) trapezoidal strips and compare with the exact analytical formula \(W = \frac{P_2 V_2 - P_1 V_1}{1 - n}\).
  2. Pipe Diameter Economic Tradeoff (Fluid Mechanics): For water flowing at \(Q = 0.045\text{ m}^3/\text{s}\) across a \(120\text{-m}\) horizontal pipe (\(f \approx 0.021\)), loop over standard commercial diameters \(D \in [75, 100, 125, 150, 200]\text{ mm}\), print velocity \(V\) and hydraulic pumping power \(\dot{W}_{\text{pump}} = \rho g Q h_f\) (\(\text{kW}\)), and break/flag diameters exceeding \(3.0\text{ m/s}\) erosion limit.
  3. 2D Factorial Truss Stress Matrix (Nested Loop): Using nested for loops, build a table printing rod normal stress \(\sigma\) (MPa) across loads \(F \in [20, 40, 60]\text{ kN}\) and bar diameters \(d \in [16, 20, 25]\text{ mm}\).

🎬 Concept & Engineering Animation

🎬 Brayton For Loop Sweep