01 Looping over a collection
A for loop walks through a collection and hands you one item at a time. The variable after for is a name you choose — it is given each item in turn.
The colon and the indentation are not style. The colon says “a block follows” and the indentation marks where the block ends.
for_basics.py
plants = ["fern", "cactus", "ivy"]
for plant in plants:
print(plant)
# fern
# cactus
# ivy
# Strings are collections of characters
for letter in "abc":
print(letter)
02 range
range makes a sequence of numbers to count through. It takes up to three arguments, and the stop value is not included.
range(5) gives 0, 1, 2, 3, 4 — five numbers starting at zero. That off-by-one feels wrong for a week and then feels obvious, because it matches how list positions are numbered.
range.py
range(5) # 0 1 2 3 4 stop only
range(2, 6) # 2 3 4 5 start, stop
range(0, 10, 2) # 0 2 4 6 8 start, stop, step
range(5, 0, -1) # 5 4 3 2 1 counting down
for i in range(3):
print(f"pass number {i}")
# Walk a list by position when you need the index
for i in range(len(plants)):
print(i, plants[i])
03 Tracing a loop
When a loop misbehaves, stop reading it and trace it. Write down every variable at the end of each pass. Four lines of a table beats an hour of staring.
Here is the trace for a loop that totals a list.
trace_me.py
prices = [4, 7, 2]
total = 0
for price in prices:
total = total + price
print(total) # 13
what happens on each pass
04 Indentation decides what repeats
The most common loop bug in Python is not a logic error. It is a line indented one level too far, or not far enough.
In the second version the print is outside the loop, so it runs once after everything. Same five lines, completely different program — and no error message.
indentation.py
# Prints after every pass
total = 0
for price in [4, 7, 2]:
total += price
print(total) # 4, then 11, then 13
# Prints once, at the end
total = 0
for price in [4, 7, 2]:
total += price
print(total) # 13
05 while loops
A while loop repeats as long as its condition stays true. Use it when the number of passes depends on something that happens inside the loop.
Something in the body must eventually make the condition false. Forget that and the program hangs forever — press Ctrl+C in the terminal to stop it.
while.py
count = 3
while count > 0:
print(count)
count -= 1 # without this line, it never stops
print("Liftoff")
# The usual real use: keep asking until the answer is valid
answer = ""
while answer not in ("yes", "no"):
answer = input("yes or no? ").lower().strip()
06 for or while?
A short rule that covers nearly every case you will meet this year.
07 break and continue
break leaves the loop immediately. continue skips the rest of this pass and starts the next one.
break only leaves the innermost loop. To escape two nested loops you need a flag variable, or — usually better — move the inner loop into a function and return.
break_continue.py
# break - stop as soon as we find it
for plant in plants:
if plant == "cactus":
print("found it")
break
# continue - skip the ones we do not want
for n in range(10):
if n % 2 == 1:
continue # skip odd numbers
print(n) # 0 2 4 6 8
08 enumerate and zip
Two built-ins that remove the two most common reasons people fall back to range(len(...)).
enumerate gives you the index and the item together. zip walks two lists side by side, stopping when the shorter one runs out.
enumerate_zip.py
plants = ["fern", "cactus", "ivy"]
# Index and item, without counting by hand
for i, plant in enumerate(plants):
print(f"{i}: {plant}")
# Start counting at 1 instead
for i, plant in enumerate(plants, start=1):
print(f"{i}. {plant}")
# Two lists together
rooms = ["kitchen", "office", "hall"]
for plant, room in zip(plants, rooms):
print(f"The {plant} lives in the {room}")
09 Building a list in a loop
The pattern behind most useful loops: start with an empty list, append on each pass.
Once that shape is familiar, a comprehension says the same thing on one line. Use a comprehension when it fits on one readable line and a loop when it does not.
building.py
# The long form
lengths = []
for plant in plants:
lengths.append(len(plant))
# The same thing as a comprehension
lengths = [len(plant) for plant in plants]
# With a filter on the end
short = [p for p in plants if len(p) < 5]
# Counting, the common one
thirsty = 0
for plant in plants:
if needs_water(plant):
thirsty += 1
10 Loop mistakes to recognise
Each of these produces a wrong answer rather than an error, which is what makes them worth memorising.
Nothing on this page mentions that. Try a shorter word, or clear the filter.