What you'll learn
- Repeat work over ranges and lists
- Build results with the accumulator pattern
- Count with range(start, stop, step) without off-by-one errors
- Write a while loop that is guaranteed to stop
Repeat work over ranges and lists with for loops, and loop until a condition changes with while.
Why it matters
Computers are good at doing the same thing many times without getting bored or making mistakes. Adding up a thousand readings, checking every row of a file, retrying a calculation until it converges: all of these are loops. Python has two kinds. A for loop goes through a collection item by item. A while loop keeps going as long as a condition is true.
for loops over a list
readings = [21.5, 22.0, 23.25, 22.75]
for value in readings:
print("Reading:", value)Read it as "for each value in readings, run the indented block". On each pass, called an iterationOne pass through the body of a loop., the loop variable value holds the next item. The loop ends by itself after the last item.
You can loop over any collection, including the characters of a string:
for letter in "DNA":
print(letter) # D, then N, then AThe accumulator pattern
The most common loop builds up a result. Start with an empty or zero value before the loop, update it inside, and use it after:
readings = [21.5, 22.0, 23.25, 22.75]
total = 0
count = 0
for value in readings:
total += value
count += 1
print(f"Average: {total / count:.2f}") # Average: 22.38The same pattern finds a maximum, counts matches or collects values into a new list:
high = []
for value in readings:
if value > 22:
high.append(value) # append adds an item to the end of a list
print(high) # [23.25, 22.75](Python also has built-ins such as sum, max and len for the simple cases. Knowing the pattern lets you handle the cases they do not cover.)
Counting with range
range produces a sequence of whole numbers, which is how you repeat something a fixed number of times:
for i in range(5):
print(i) # 0 1 2 3 4 (stops BEFORE 5)
for year in range(2020, 2025):
print(year) # 2020 to 2024
for n in range(10, 0, -2):
print(n) # 10 8 6 4 2 (a step of -2)range(start, stop, step) includes start and excludes stop. That "up to but not including" rule is everywhere in Python, and it is the source of many off-by-one bugs. To add the numbers from 1 to 100 you need range(1, 101).
If you need both the position and the item, use enumerate:
for position, name in enumerate(["Ada", "Grace", "Katherine"], start=1):
print(position, name) # 1 Ada / 2 Grace / 3 Katherinewhile loops
Use while when you do not know in advance how many iterations you need, only when to stop:
balance = 1000.0
years = 0
while balance < 2000:
balance *= 1.05 # 5% growth each year
years += 1
print(f"Doubles after {years} years") # Doubles after 15 yearsPython checks the condition before every iteration. When it becomes false, the loop ends. Something inside the loop must eventually make the condition false, or the loop runs forever. If your program seems frozen, an infinite while loop is the usual suspect (the browser runner stops it after a few seconds; in a terminal, press Ctrl+C).
break and continue
breakleaves the loop immediately.continueskips the rest of this iteration and moves to the next one.
values = [4, 8, -1, 15, 16]
for v in values:
if v < 0:
print("Found a negative value, stopping")
break
print("Processing", v)
for v in values:
if v < 0:
continue # skip bad data, keep going
print("Valid:", v)Nested loops
A loop inside a loop runs the inner loop completely for each pass of the outer one. A multiplication table is the classic example:
for row in range(1, 4):
line = ""
for col in range(1, 4):
line += f"{row * col:4}"
print(line)Output:
1 2 3
2 4 6
3 6 9Common mistakes
- Off by one with rangeA built-in that produces whole numbers from start up to but not including stop, in steps..
range(1, 10)stops at 9. Ask yourself whether the last value should be included. - Resetting the accumulator inside the loop. If
total = 0sits inside the loop, it is wiped on every pass. Put it before the loop. - Forgetting to update the whileA loop that repeats as long as its condition is true, checked before every iteration. condition. No
years += 1orbalance *= ...means an infinite loop. - Changing a list while looping over it. Removing items from the list you are looping over skips elements. Build a new list instead.
- Wrong indentation. A line indented under the loop runs every time; a line at the outer level runs once, after the loop. Moving a
printone level in or out changes the output completely.
Quick recap
for item in collection:visits each item once.- Accumulator patternSetting up a result before a loop, updating it inside, and using it after.: set up before, update inside, use after.
range(start, stop, step)counts and excludesstop.while condition:repeats until the condition is false; make sure it can become false.breakexits a loop;continueskips to the next iteration.
Try it
In the Do tab you will write a for loop that sums a range of numbers, another that counts values above a threshold, and a while loop that finds how many years an investment takes to double.
Key terms (6)
- iteration
- One pass through the body of a loop.
- accumulator pattern
- Setting up a result before a loop, updating it inside, and using it after.
- range
- A built-in that produces whole numbers from start up to but not including stop, in steps.
- enumerate
- A built-in that gives both the position and the item on each pass of a loop.
- while
- A loop that repeats as long as its condition is true, checked before every iteration.
- break
- A statement that leaves a loop immediately; continue instead skips to the next iteration.