Teach Your Kids To Code: A Parent-friendly Guide to Python Programming

(vip2019) #1
Turtle Graphics: Drawing with Python 21

The next thing we need to do is change the pen color every time
we step through the drawing loop. To do this, we need to move the
t.pencolor() function into the group of instructions under the for
loop. We also need to tell the pencolor function that we want to use
one of the colors from the list.
Type the following code and run it.


ColorSquareSpiral.py


import turtle
t = turtle.Pen()
colors = ["red", "yellow", "blue", "green"]
for x in range(100):
t.pencolor(colors[x%4])
t.forward(x)
t.left(91)


The list of four colors makes sense, and we can see them in the
running example (Figure 2-5). So far, so good.


Figure 2-5: A much more colorful version of
our square spiral program


The only new part is the (colors[x%4]) in the pencolor function.
The x inside the statement is the same variable we’re using else-
where in the program. So x will continue to grow from 0 to 99, just
like we’ve seen before. The colors variable name inside the paren-
theses tells Python to choose a color from the list of color names
called colors that we added earlier in the program.
The [x%4] part tells Python that we will use the first four colors
in the colors list, numbered 0 through 3, and rotate through them

Free download pdf