Module 1 · Section 4 of 10
Lesson 1.3 - Control Flow
Target: ~10 min read - 20 min hands-on
Overview
if/elif/else lets you branch; for and while loops let you repeat. A pattern that
shows up in every field: checking a batch of readings against limits, and iterating a
calculation until it converges. Doing this by hand for a handful of values is fine - for
hundreds, across many channels, it's exactly the repetitive, error-prone task Python
eliminates.
Caution: if a while loop's condition never becomes False, you get an infinite loop.
Why This Matters (PH Context)
Condition-monitoring and QA/QC programs at PH plants, utilities, and factories run rules like "alarm below 90% of nominal voltage" or "reject outside +/- 0.05 mm" continuously against logged data. Automating the check with a loop instead of scanning a spreadsheet by eye is one of the fastest wins a junior engineer can bring to any team.
Code-Along
# Lesson 1.3 - Control flow: if/elif/else and loops
# --- if / elif / else: run exactly ONE branch, based on conditions ---
# [Electrical] is a measured supply voltage within +/-10% of nominal?
nominal_V = 230.0
measured_V = 198.0
low, high = nominal_V * 0.90, nominal_V * 1.10 # tolerance band edges
if measured_V < low:
verdict = "UNDERVOLTAGE"
elif measured_V > high: # checked only if the first test was False
verdict = "OVERVOLTAGE"
else: # runs if none of the above matched
verdict = "WITHIN TOLERANCE"
print(f"{measured_V} V vs {nominal_V} V nominal -> {verdict}")
# --- for loop: repeat a block once per item in a sequence ---
# [Industrial] check each measured part against target +/- tolerance
target_mm, tol_mm = 25.00, 0.05
samples = [25.01, 24.97, 25.06, 24.93, 25.00, 25.04]
passed = 0
# enumerate(..., start=1) yields (1, first_item), (2, second_item), ...
for i, d in enumerate(samples, start=1):
ok = abs(d - target_mm) <= tol_mm # abs() = distance from target, sign ignored
passed += ok # a bool adds as 1 (True) or 0 (False)
print(f" part {i}: {d:.2f} mm -> {'PASS' if ok else 'FAIL'}") # inline if/else
print(f"{passed}/{len(samples)} parts within tolerance")
# --- while loop: repeat UNTIL a condition becomes False ---
# [Computer] Newton-Raphson: each pass roughly doubles the correct digits
number = 150.0
guess = number / 2
iterations = 0
while abs(guess * guess - number) > 1e-6: # stop once guess^2 is close enough
guess = 0.5 * (guess + number / guess) # the update rule
iterations += 1 # counting the passes guards vs an infinite loop
print(f"sqrt({number}) = {guess:.6f} in {iterations} iterations")
Expected output:
198.0 V vs 230.0 V nominal -> UNDERVOLTAGE
part 1: 25.01 mm -> PASS
part 2: 24.97 mm -> PASS
part 3: 25.06 mm -> FAIL
part 4: 24.93 mm -> FAIL
part 5: 25.00 mm -> PASS
part 6: 25.04 mm -> PASS
4/6 parts within tolerance
sqrt(150.0) = 12.247449 in 6 iterations
Practice Exercises
- [Chemical] Given five batch pH readings, loop through and print
"IN SPEC"if a reading is between 6.5 and 7.5 inclusive, else"OUT OF SPEC". - [Mechanical] Write a
whileloop that starts a pump flow at 10 L/s, increases it by 2 L/s each step, until it reaches or exceeds 50 L/s. Print the number of steps. - Debug it:
count = 0
while count < 5:
print("Iteration", count)
# Try the practice exercises here
Knowledge Check
- What is the risk of a
whileloop whose condition never becomes False? - In an
if/elif/elsechain, how many branches can execute? - Which loop is best suited to iterate through a fixed list of QC samples?
Answer key
- Infinite loop
- Exactly one
for
4 / 63 sections · Course home · Join the coaching cohort