Repeating Work with Loops · practice
Loop Over a List
Reading a
Watch the loop variable change
The loop
Run that and follow size through the passes. On the first pass it holds 8. Python reaches the end of the body, jumps back to the for line, and size becomes 12. Then 16. After the last
That reassignment is easy to describe and much better to watch. You will do exactly that in the exercise at the end of this lesson, using the Step button in the editor.
A body can hold several lines
Everything indented under the for line runs on every pass, in order:
Six lines from the loop, then one line after it. Notice how the two indented lines stay together as a group and the last line stands apart.
The loop variable holds one item, not the list
A common early tangle is mixing up the
price is a single number on each pass. prices is still the full list, before and after the loop.
Three mistakes worth meeting now
You will make each of these at some point. Meeting them here makes them easier to recognize later.
A missing colon. Python stops with a for line:
for guest in guests
print(guest)
A missing indent. Python expects an indented block after the colon and reports an IndentationError:
for guest in guests:
print(guest)
Looping over the wrong name. This one does not crash, which makes it sneakier. Looping over a single
If your loop produces single characters when you expected whole items, check whether you wrote the singular name where you meant the plural one.
What does this code print?
notes = ["do", "re", "mi"]
for note in notes:
print(note.upper())
print("end")After a for loop finishes, its loop variable keeps the last value it received. Python does not clear the name automatically.
An empty list supplies no value at all. In that case, the loop does not create its loop variable or change an existing variable with that name.
After this loop finishes, what is the value of bird?
birds = ["robin", "swift", "wren"]
for bird in birds:
print(bird)
Now write a loop of your own.
Task
The plants
uses a
forwith plantas the loop; prints one line per plant in the form
Water the fern., with the plant name in place offernand a period at the end;keeps the final summary line, which runs once after the loop.
Expected output:
Water the fern.
Water the basil.
Water the aloe.
Water the ivy.
Plants to water: 4
Add a fifth plant to the list and run the program again. The loop should handle it without any other change. Remove it before you submit.
See the loop variable change
Once your loop runs, press Step in the editor toolbar and move forward one line at a time with Next. Watch plant in the variables panel.
You will see the highlight travel down the loop body, jump back up to the for line, and plant take the next fern, then basil, then aloe, then ivy. That jump back is the loop, and it is worth seeing once with your own code.