22 Chapter 2
every time x changes. In this case, our color list only has four colors,
so we’ll rotate through these four colors over and over:
colors = ["red", "yellow", "blue", "green"]
0 1 2 3
The % symbol in [x%4] is called the modulo, or mod, operator
and represents the remainder in long division (5 ÷ 4 equals 1 with
a remainder of 1, because 4 goes evenly into 5 once with 1 left over;
6 ÷ 4 has a remainder of 2; and so on). The mod operator is useful
when you want to rotate through a certain number of items in a
list, like we’re doing with our list of four colors.
In 100 steps, colors[x%4] will loop through four colors (0, 1, 2,
and 3, for red, yellow, blue, and green) a total of 25 times. If you
have the time (and a magnifying glass), you could count 25 red,
25 yellow, 25 blue, and 25 green segments in Figure 2-5. The first
time through the drawing loop, Python uses the first color in the
list, red; the second time, it uses yellow; and so on. Then the fifth
time through the loop, Python goes back to red, then yellow, and
so on, and always cycles back around to red after every fourth pass
through the loop.