Need to repeat work until a condition changes? Use a `while` loop. Python checks its condition before each iteration, runs the body while the condition is `True`, and exits when it becomes `False`. Make sure the body can change the condition when the work should end. section 5.4
Repeat until a threshold
`n = 1` `while n < 3:` ` print(n)` ` n += 1` Output: `1` `2` After the second iteration, `n` becomes 3, so the next condition check ends the loop. section 5.4
When the work instead depends on the items in an iterable, prefer a `for` loop: `for task in tasks:` applies the body to each task. Python obtains an iterator and handles exhaustion automatically; you normally do not need to call `iter()` or `next()` yourself. section 5.4.4 section 5.1.1
Stop after finding a match
`found = None` `for task in tasks:` ` if task.urgency == 5:` ` found = task` ` break` `break` exits immediately, avoiding checks of later tasks. Initialize `found` first so it remains usable when no task matches. section 5.4.1
Keep loops readable:
- Use `enumerate(items, start=1)` when you need both an item and its position, rather than indexing through `range(len(items))`. section 1.4.1
- Prefer explicit nested `for` loops over a deeply nested comprehension when the separate layers are easier to follow. section 5.2.6
- A loop’s `else` runs after normal completion but not after `break`. Use it cautiously: it can confuse readers, and it adds nothing when the loop has no `break`. section 5.4.3 section 5.4.4


























