Python 2.3The video for this lesson is on its way.
Everything else is ready: study the parts, the key terms and the quiz below.
- Part 11One loop, two ways
- Part 22The for loop: the loop variable, and what it can loop over
- Part 33Totals, averages and counts
- Part 44A string is a sequence too
- Part 55range: a sequence of whole numbers
- Part 66enumerate and zip
- Part 77Where for loops mislead
- Part 88Nested loops
- Part 99Recap and your challenge
Python 2.3Code walkthrough9 parts
for Loops and range
Iterate over any sequence.
Loading your progress…Next: 2.4 break, continue and else on Loops
In this lesson9 parts
- 01One loop, two ways
- 02The for loop: the loop variable, and what it can loop over
- 03Totals, averages and counts
- 04A string is a sequence too
- 05range: a sequence of whole numbers
- 06enumerate and zip
- 07Where for loops mislead
- 08Nested loops
- 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
forloop can go through, one item at a time: a list, a string, arange. - 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
forloop binds to each item in turn:stepsinfor 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)gives0,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.