Python Foundations·Lesson 9 of 67·beginner
Repeating work
for and while loops, range, enumerate and zip — and the three keywords that let you steer a loop from the inside.
In this lesson · 15 min
- →Loop over any sequence with for
- →Generate number sequences with range
- →Use enumerate and zip instead of manual index arithmetic
- →Control flow inside a loop with break, continue and else
- →Know when a while loop is the right choice
A for loop runs a block once for each item in a sequence. This is the loop you will write
almost every time.
Notice there is no counter and no index. Python hands you each item directly. The same loop works on anything iterable:
range for counting
When you genuinely need numbers, range produces them.
range is lazy — it does not build a list, it produces numbers one at a time. range(10**9)
costs nothing until you iterate it.
enumerate when you need the position too
The beginner reflex is to loop over indices. Resist it.
zip to walk two sequences together
zip stops at the shortest sequence, which is usually what you want and occasionally a silent
bug — pass strict=True to make a length mismatch raise instead.
Steering a loop from inside
break leaves the loop immediately.
continue skips to the next iteration.
else on a loop runs only if the loop finished without breaking. It is unusual, but it
is exactly right for search loops:
while for “until something changes”
Use while when you do not know how many iterations you need in advance.
The danger with while is forgetting to change the condition:
Press Stop — the interpreter is restarted and the page stays responsive. On your own
machine this is Ctrl+C.
Accumulating results
The pattern behind almost every data script:
That last line is a generator expression — a comprehension without the brackets, computing values one at a time instead of building a list first.
Try it yourself
Print a numbered leaderboard, highest score first, in the form 1. ensemble 93% — one line per model.
Find the position of the first score at or above 0.85 and store it in found_at. If there is none, leave it as -1.
Check yourself
What does list(range(1, 10, 3)) produce?
Recap
for item in sequenceis the default loop; you rarely need indices.range(start, stop, step)counts lazily, withstopexcluded.enumerategives you position and item;zipwalks several sequences together.breakexits,continueskips, andelseon a loop runs only if nothing broke out.- Use
whilewhen the number of iterations depends on something that changes.