Lesson 3 of 3
Repeat code until a condition changes with while, avoid infinite loops, and control loops with break and continue.
About 25 minutes
while loop that stops when its condition becomes falsebreak and continue to control a loopfor loop and a while loopA for loop repeats once per item, so you know in advance how many times it will run. Sometimes you don't: you want to keep going until something happens, such as a value converging or a sample cooling below a threshold. A while loop repeats its block as long as its condition is True.
Python checks the condition before each repetition. If it is True, the block runs and Python checks again; once it is False, the loop ends and the program continues after it. If the condition is False from the start, the block never runs at all.
temperature = 900.0 # °Cminutes = 0while temperature > 100: temperature = temperature * 0.8 # loses 20% each minute minutes += 1print(f"Below 100 °C after {minutes} minutes ({temperature:.1f} °C)")Infinite loops
False. If you forget to update temperature above, the condition stays True forever and the program never ends. In SPASCLE's editor, a program that runs for more than 10 seconds is stopped automatically, so you can experiment safely.Grain growth: an average grain size grows by 15% per hour of annealing. How long until it exceeds 50 µm?
grain_size = 12.0 # µmhours = 0while grain_size <= 50: grain_size *= 1.15 hours += 1print(f"{hours} hours of annealing gives {grain_size:.1f} µm grains")break ends the loop immediately, even if the condition is still True (or, in a for loop, even if items remain). It is useful when you are searching for something and can stop as soon as you find it.
readings = [8.95, 8.97, 9.85, 8.96, 8.94]for index, reading in enumerate(readings): if reading > 9.5: print(f"Faulty reading {reading} at position {index}; stopping.") break print("OK:", reading)A common pattern is while True: with a break inside. The loop would run forever on its own, so the break is the only way out. This suits iterative calculations that stop once the answer is accurate enough. The example below finds √2 with Newton's method, improving its guess until the change is tiny.
target = 2.0guess = 1.0steps = 0while True: better_guess = (guess + target / guess) / 2 steps += 1 if abs(better_guess - guess) < 1e-10: break guess = better_guessprint(f"√{target} ≈ {better_guess:.10f} after {steps} steps")continue skips the rest of the current repetition and goes straight to the next one. Use it to ignore items you don't want to process, such as missing values.
readings = [293.1, None, 294.0, None, 292.7]total = 0count = 0for reading in readings: if reading is None: continue # skip missing values total += reading count += 1print(f"Mean of {count} valid readings: {total / count:.2f} K")None is Python's value for nothing. It is often used to mark a missing measurement. Check for it with is None.
| Use | When |
|---|---|
for | You are working through a collection, or you know how many repetitions you need. This is the most common case. |
while | You repeat until a condition changes and can't know in advance how many repetitions it will take: convergence, thresholds, waiting for valid input. |
Choose an answer and press Check answer. You can retry as often as you like.