Python 2.3Code walkthrough9 parts

for Loops and range

Iterate over any sequence.

In this lesson9 parts

  1. 01One loop, two ways
  2. 02The for loop: the loop variable, and what it can loop over
  3. 03Totals, averages and counts
  4. 04A string is a sequence too
  5. 05range: a sequence of whole numbers
  6. 06enumerate and zip
  7. 07Where for loops mislead
  8. 08Nested loops
  9. 09Recap and your challenge

Key terms

The words this lesson introduces, each in one line. The module’s glossary collects them all.

accumulator
A name that collects a result across a loop's iterations. It is created before the loop (total = 0), updated in the body (total += steps), and read after it.
iterable
Anything a for loop can go through, one item at a time: a list, a string, a range.
list
Values in square brackets, in order, separated by commas: [8200, 10450, 6300]. Module 2 uses lists only in loops; Python 3.1 teaches them.
loop variable
The name a for loop binds to each item in turn: steps in for steps in week:. It keeps its last value after the loop.
nested loop
A loop inside the body of another loop. The inner loop runs in full for every iteration of the outer one.
range
A sequence of whole numbers from a start, up to but not including a stop, with an optional step: range(0, 20, 5) gives 0, 5, 10, 15. It works each number out when the loop asks for it.

Quiz 5 questions

Your first pick on each question is the one that counts, and a right one earns a coin. Getting one wrong here is how the lesson sticks.

Practice

Problems to solve in your own notebook. Each states the problem, not the steps: working out the steps is the exercise. Level A applies the lesson, B combines it with earlier ones, C stretches it.

The self-checking notebook for this lesson is Notebook 2 · Loops.

Common mistakes

What you will see when it goes wrong, why it happens, and the fix.

Where it’s used

Where this lesson’s ideas turn up in real work.