liveBook · Manning

Loop

As explained in Python How-To

A while loop repeatedly executes a block of code while a Boolean condition remains true.

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

How Python How-To covers it

How deep it goes
Works through condition checks, iterator exhaustion, early exit, and loop `else`, then gives maintainability guidance.
Examples
Uses a changing counter, task searches, and nested product-option generation.
What it assumes
Assumes familiarity with the basic `for` form while explaining `while` conditions and the iterator mechanism.
What you can do after
Practice/perform repeated work with `while` or `for`, and stop a search once a match appears.
How it connects
Connects loops to iterables, iterators, `enumerate`, comprehensions, `break`, and `else`.

Also explained in

Compare how 27 books explain loop →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.