Lesson 08: for Loops, Accumulators & Parametric Environmental Sweeps

The β€œBoring Stuff” Problem: Repeating Calculations Across 200 River Miles or 1,030 Concrete Mixes

Suppose you need to check river dissolved oxygen at 0, 10, 20, ..., 100 km downstream of a treatment outfall, OR scan 1,030 structural concrete mixes in UCI_Concrete_LowCarbon_SCMs.csv to identify mixes that slash Portland cement content (LCA Track 1) while maintaining strength.

Think of a for loop as a conveyor belt: Python picks up one item at a time, runs your indented code block, updates running accumulators (total, count, worst_deficit), and moves automatically to the next item.

Three superpowers make for loops clean and bug-free:

  1. range(start, stop, step): Remember stop is excluded, so range(0, 101, 10) includes 100.
  2. zip(list_a, list_b): Loops over paired measurements in lockstep instead of error-prone index counting a[i], b[i].
  3. enumerate(items, start=1): Gives both item number and value simultaneously!
import math

# Example 1 (River Water Quality): Streeter-Phelps Downstream DO Sag & Critical Deficit Tracker
# L0 = 24.0 mg/L ultimate BOD after mixing, D0 = 1.2 mg/L initial DO deficit, DO_sat = 9.2 mg/L
# u_river = 25.0 km/day, kd = 0.25 1/day (deoxygenation), kr = 0.55 1/day (reaeration)
L0, D0, DO_sat = 24.0, 1.2, 9.2
u_km_d, kd, kr = 25.0, 0.25, 0.55

min_do = 999.0
crit_km = 0.0
print("Dist [km] | Time [d] | BOD Rem [mg/L] | Deficit [mg/L] | River DO [mg/L]")
print("-" * 74)
for x_km in range(0, 151, 15):
    t = x_km / u_km_d
    bod_t = L0 * math.exp(-kd * t)
    D_t = (kd * L0 / (kr - kd)) * (math.exp(-kd * t) - math.exp(-kr * t)) + D0 * math.exp(-kr * t)
    do_t = DO_sat - D_t
    if do_t < min_do:
        min_do, crit_km = do_t, x_km
    flag = " <-- LOW DO!" if do_t < 4.0 else ""
    print(f"{x_km:9d} | {t:8.2f} | {bod_t:14.2f} | {D_t:14.2f} | {do_t:14.2f}{flag}")

print(f"\nWorst Sampled Point: {min_do:.2f} mg/L near x = {crit_km} km downstream")
Dist [km] | Time [d] | BOD Rem [mg/L] | Deficit [mg/L] | River DO [mg/L]
--------------------------------------------------------------------------
        0 |     0.00 |          24.00 |           1.20 |           8.00
       15 |     0.60 |          20.66 |           3.70 |           5.50
       30 |     1.20 |          17.78 |           5.10 |           4.10
       45 |     1.80 |          15.30 |           5.77 |           3.43 <-- LOW DO!
       60 |     2.40 |          13.17 |           5.95 |           3.25 <-- LOW DO!
       75 |     3.00 |          11.34 |           5.84 |           3.36 <-- LOW DO!
       90 |     3.60 |           9.76 |           5.54 |           3.66 <-- LOW DO!
      105 |     4.20 |           8.40 |           5.13 |           4.07
      120 |     4.80 |           7.23 |           4.68 |           4.52
      135 |     5.40 |           6.22 |           4.22 |           4.98
      150 |     6.00 |           5.36 |           3.77 |           5.43

Worst Sampled Point: 3.25 mg/L near x = 60 km downstream
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/")
# Example 2 (Real UCI Data + LCA Low-Carbon Materials): Scanning 1,030 Mixes in UCI_Concrete_LowCarbon_SCMs.csv
# Blast furnace slag & fly ash are industrial byproducts replacing carbon-intensive Portland cement!
rows = data_file("UCI_Concrete_LowCarbon_SCMs.csv").read_text(encoding="utf-8").splitlines()[1:]

low_carbon_high_strength = 0
max_scm_pct = 0.0
total_mixes = 0

for row in rows:
    cols = [float(x) for x in row.split(",")]
    cement, slag, fly_ash, strength_mpa = cols[0], cols[1], cols[2], cols[8]
    binder_total = cement + slag + fly_ash
    scm_frac = (slag + fly_ash) / binder_total
    total_mixes += 1
    if scm_frac > max_scm_pct:
        max_scm_pct = scm_frac
    if scm_frac >= 0.40 and strength_mpa >= 40.0:
        low_carbon_high_strength += 1

print("=== Real UCI Low-Carbon Concrete Byproduct Audit (1,030 Laboratory Mixes) ===")
print(f"Total Mixes Audited         : {total_mixes}")
print(f"Max SCM Clinker Replacement : {max_scm_pct:.1%}")
print(f"High-Performance Green Mixes (>=40% SCM AND >=40 MPa): {low_carbon_high_strength} mixes")
=== Real UCI Low-Carbon Concrete Byproduct Audit (1,030 Laboratory Mixes) ===
Total Mixes Audited         : 1030
Max SCM Clinker Replacement : 73.6%
High-Performance Green Mixes (>=40% SCM AND >=40 MPa): 82 mixes

Concept Check Questions

  1. Why did Example 1 initialize min_do = 999.0 before starting the for loop instead of inside it?
  2. What would range(0, 150, 15) miss compared to range(0, 151, 15)?
  3. Why is zip(flows, emission_factors) cleaner than writing for i in range(len(flows)):?

Guided Practice Problem 1: Accumulate Total Storm Nutrient Load (zip Practice)

Given 6 hourly stream gauge measurements of flow \(Q = [12.0, 18.5, 31.0, 27.4, 20.1, 15.0]\text{ m}^3/\text{s}\) paired with nitrate concentration \(C = [1.8, 3.4, 6.2, 5.1, 3.8, 2.3]\text{ mg/L}\), use a for ... zip(...) loop to compute total storm water volume (\(\text{m}^3\)), total \(\text{NO}_3\text{-N}\) mass (\(\text{kg}\)), and Flow-Weighted Mean Concentration (\(\text{mg/L}\)).

# Guided Practice 1 Starter
Q_list = [12.0, 18.5, 31.0, 27.4, 20.1, 15.0]
C_list = [1.8, 3.4, 6.2, 5.1, 3.8, 2.3]
vol_m3, mass_kg = 0.0, 0.0
for q, c in zip(Q_list, C_list):
    d_vol = q * 3600.0
    vol_m3 += d_vol
    mass_kg += d_vol * c * 1e-3
print(f"Total Volume = {vol_m3:,.0f} m^3 | Nitrate Mass = {mass_kg:.1f} kg | FWMC = {mass_kg*1e3/vol_m3:.2f} mg/L")
Total Volume = 446,400 m^3 | Nitrate Mass = 1898.4 kg | FWMC = 4.25 mg/L