Skip to content

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.

PythonPython not started

Notice there is no counter and no index. Python hands you each item directly. The same loop works on anything iterable:

PythonPython not started

range for counting

When you genuinely need numbers, range produces them.

PythonPython not started

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.

PythonPython not started

zip to walk two sequences together

PythonPython not started

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.

PythonPython not started

Steering a loop from inside

break leaves the loop immediately.

PythonPython not started

continue skips to the next iteration.

PythonPython not started

else on a loop runs only if the loop finished without breaking. It is unusual, but it is exactly right for search loops:

PythonPython not started

while for “until something changes”

Use while when you do not know how many iterations you need in advance.

PythonPython not started

The danger with while is forgetting to change the condition:

PythonPython not started

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:

PythonPython not started

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

Exercise 1

Print a numbered leaderboard, highest score first, in the form 1. ensemble 93% — one line per model.

Your turnPython not started
Exercise 2

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.

Your turnPython not started

Check yourself

What does list(range(1, 10, 3)) produce?

Recap

  • for item in sequence is the default loop; you rarely need indices.
  • range(start, stop, step) counts lazily, with stop excluded.
  • enumerate gives you position and item; zip walks several sequences together.
  • break exits, continue skips, and else on a loop runs only if nothing broke out.
  • Use while when the number of iterations depends on something that changes.