Loops & Iteration
A loop is the machine's superpower: do the same thing again and again without getting bored or making a typo on repetition nine thousand. A for loop runs a known number of laps โ "for each item on this list" โ and hands you one item per lap. A while loop keeps lapping as long as a condition stays true โ "while the pot is not boiling, keep waiting" โ which is perfect when you cannot know the lap count in advance, and dangerous for the same reason: if the condition never turns false, the program runs forever. Two escape hatches: break leaves the track immediately; continue skips the rest of THIS lap and starts the next one.
Laps around the track
step 1 / 7Three prices on the track, an empty accumulator waiting. The loop will visit each item exactly once.total = 0
Loop constructs side by side
| intent | Python | JavaScript |
|---|---|---|
| each item | for x in items: | for (const x of items) |
| index + item | for i, x in enumerate(items): | items.forEach((x, i) => โฆ) |
| counted | for i in range(n): | for (let i = 0; i < n; i++) |
| until condition | while not done: | while (!done) |
| keys of a mapping | for k in d: / d.items() | for (const k in obj) / Object.entries |
| transform | [x * 2 for x in xs] | xs.map(x => x * 2) |
| filter | [x for x in xs if x > 0] | xs.filter(x => x > 0) |
The universal rules
- break exits the loop; continue skips to the next lap โ both apply to the INNERMOST loop only.
- Never mutate the collection you are iterating โ copy it or build a new one.
- Nested loops over the same data multiply: n ร n = the O(nยฒ) alarm from Counting Steps.
- Every while needs a visible progress line; if you can't point to it, it's infinite.
Python extras
- for/else exists: the else runs only if the loop finished WITHOUT break โ perfect for search-then-not-found.
- zip(a, b) walks two lists in lockstep; itertools has the rest (pairwise, product, chain).
- range is lazy โ range(10**12) costs 48 bytes; list(range(10**12)) costs your RAM.
total = 0
for price in [4, 7, 2]: # known laps
total += price
print(total) # 13
n = 1
while n < 100: # unknown laps
n = n * 2
print(n) # 128
for i, ch in enumerate("abc"):
print(i, ch) # 0 a / 1 b / 2 cHow many times does the inner body run? for i in range(4): for j in range(3): body()
sum_prices(prices) loops over a list of numbers and returns their total. The accumulator pattern: init before, update inside, return after.