Step 1 of 8 · Reading · ~4 min
Learn
Loops and Iteration
For Loops
A for loop runs the same block of code once for every value in a sequence. By the end of this lesson you can count with range(), walk through the characters of a word, and build a single answer - a sum, a count, a largest-so-far - out of many small steps.
The shape of a loop
tick
tick
tick
Read the header as "for each value in this sequence, call it hour, then run the indented block." Four pieces must be present: the keyword for, a loop variable that is given a new value on every pass, the keyword in followed by something you can iterate over, and a colon followed by an indented body. The body is every line indented under the header. The first line that is not indented runs once, after the loop has finished.
The loop variable is an ordinary variable, so you can use its value:
hour 0
hour 1
hour 2
Notice where it started and where it stopped.
range() has three forms
range() generates whole numbers on demand. It takes one, two, or three arguments:
With one argument it counts from 0. With two, the first is the start. With three, the last is the step, and a negative step counts down.
In every form the stop value is excluded. range(2, 6) ends at 5, not 6. So a loop that must count from 1 up to and including some number needs one more than that number as the stop: the numbers 1 through 7 are range(1, 8), and the numbers 1 through 30 are range(1, 31). This single rule is behind most beginner loop bugs.
Looping over a string
Any sequence works, not only numbers. A string is a sequence of characters:
c!
a!
t!
The body ran three times because the string has three characters.
Index and value together
A list is several values written inside square brackets and separated by commas. enumerate() walks a sequence and hands you the position along with the value:
1 red
2 green
3 blue
Without start=1 the positions begin at 0. A related helper, zip(), walks two sequences in lockstep and stops as soon as the shorter one runs out:
red 8
green 9
"blue" never appears: sizes had only two values.
Building one answer out of many
Most loops exist to produce a single result. Create the accumulator variable before the loop and update it inside:
10
Trace it: total is 0 before the loop, then 1, then 3, then 6, then 10. print(total) is deliberately outside the body - indent it under the loop and you get four lines of partial sums instead of one answer.
Common mistakes
- Stopping one short.
range(1, 7)ends at 6, so a report meant to cover 1 through 7 prints only six lines and the last one is missing entirely. - Starting at zero by accident.
range(7)begins at 0, so the first pass works on the value 0 and you get an extra leading line before the one you wanted. - Joining text and a number with
+.print("row " + count)raisesTypeError: can only concatenate str (not "int") to strwhencountis a whole number. Use an f-string such asf"row {count}", or convert withstr(count). - Indenting the wrong line. A
printinside the body runs on every pass; the sameprintoutside it runs once. Nothing in the logic tells you which is right - only the output format does.
Your exercise
Print a whole multiplication table for one number read from input, one product per line, using a loop over the numbers 1 to 10. The starter already reads the number and prints nothing else, so every test fails until you add the loop. The mistake to watch for is the stop value of range(): the table has to include 10 and must not begin at 0.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…