Loop patterns: totals, best so far, flags and break
A handful of loop shapes cover most everyday work.
- Running total: start a variable before the loop and update it each pass; append it to a list to keep the history, like a bank balance.
- Best so far: keep the best value and the item it belongs to. Start with
None and test best is None or value > best, so an empty list returns None instead of failing. Use > rather than >= to keep the first of tied items.
- Flag and break: set
found = None, and when the item turns up, store it and break.
- Loop else: a
for loop's else block runs only when the loop finished without break.
- Streaks: count the current run and reset it when the run ends. Check the final run after the loop, because a streak can end with the data.
continue skips the rest of one pass and moves to the next item.
temps = [21.5, 23.0, 19.8, 23.0]
best_day, best = None, None
for day, t in enumerate(temps, start=1):
if best is None or t > best:
best_day, best = day, t
best_day, best
Out: (2, 23.0). Day 4 ties at 23.0, but > keeps the first.