for: Every Item in Turn
Once information is in a list, you usually want to do the same thing to every item: print it, check it, add it to a total. Writing the same line once per item would work for three items and fall apart at three hundred. A loop runs a block of lines once for every item, and for is Python's everyday loop.
Think of a teacher marking a stack of papers. The same steps for every paper, a running tally kept on the side, and the final number announced when the stack is done. That is almost exactly the shape of the most common loop in programming.
for Each Item
A for line reads almost like English: for temp in temps. The name after for, here temp, points at each item in turn. The indented block runs once for each item, and then the program carries on after the loop. You choose the name; pick one that reads well with the list's name.
temps = [18, 22, 25, 19, 30, 27, 21] for temp in temps: print(f"{temp} degrees") print("That was the week.")
18 degrees 22 degrees 25 degrees 19 degrees 30 degrees 27 degrees 21 degrees That was the week.
Counting with range
When you need to repeat something a number of times rather than walk a list, range produces the numbers for you. range(5) gives 0, 1, 2, 3 and 4: five numbers, starting at zero and stopping before 5, just like a slice. range(1, 4) gives 1, 2 and 3.
for n in range(3, 0, -1): print(n) print("Go!")
3 2 1 Go!
The third number in that range is the step: minus one counts down. Start at 3, stop before 0, step by minus one.
The Running Total
Adding up a list is the pattern behind sums, counts and averages everywhere, and it has exactly three parts in three places. Before the loop, set the total to zero, once. Inside the loop, add the current item to it. After the loop, print or use the result.
temps = [18, 22, 25, 19, 30, 27, 21] total = 0 for temp in temps: total = total + temp print(f"Average: {total / len(temps):.1f}")
Average: 23.1
The classic mistake is to put the print inside the loop by indenting it one level too far. The program then prints a partial total after every item, three lines instead of one. The difference is only four spaces, which is why indentation deserves your attention.
temps = [18, 22, 25] total = 0 for temp in temps: total = total + temp print(f"Total: {total}")
Total: 18 Total: 40 Total: 65
Counting and Finding
The same shape answers other questions. To count, start at zero and add one when an item matches, such as every day above 25 degrees. To find, walk the list until an item matches and stop there, which the next topic's break makes possible.
temps = [18, 22, 25, 19, 30, 27, 21] hot = 0 for temp in temps: if temp > 25: hot = hot + 1 print(f"{hot} hot days")
2 hot days
- "The loop name has to be item." Any name works. Choose one that reads well, such as
for temp in temps. - "
range(5)includes 5." It stops before 5 and starts at 0, giving five numbers. - "The total resets itself each time round." It resets only if you set it to zero inside the loop. Set it once, before the loop.
- "The print can go anywhere near the loop." Indented, it runs once per item; not indented, it runs once after the loop. Four spaces decide which.
- Doing something to every item is most of what programs do with data, and
foris how Python says it. - The running total, set before, updated inside and used after, is the pattern behind sums, counts, averages and maximums in every language.
Knowledge Check
How many times does the block of for temp in [18, 22, 25]: run?
- Three times, once for each item in the list
- Once, for the whole list, all at the same time
- Twice, because counting starts at zero
- Twenty-five times, the value of the last item
Which numbers does range(1, 4) produce?
- 1, 2, 3 and 4
- 0, 1, 2 and 3
- 1, 2 and 3
- 4, 3, 2 and 1
In the running-total pattern, where does total = 0 go?
- Inside the loop, so each item starts fresh
- Before the loop, once, so the total can grow
- After the loop, just before the total is printed
- Nowhere, because Python starts every total at zero
A program prints a partial total after every item instead of one final total. What is the likely cause?
- The total was set to zero before the loop began
- The loop walked the list in the wrong order
- The list contains more items than it should
- The print is indented inside the loop by mistake
You got correct