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

(vip2019) #1

20 Chapter 2


different colors with the Turtle library, including some weird ones
like "salmon" and "lemon chiffon". (Visit http://www.tcl.tk/man/
tcl8.4/TkCmd/colors.htm for a full list.) Making the whole spiral
a different color is a nice step, but what if we wanted to make each
side a different color? That’s going to take a few more changes to
our program.

a Four-color spiral
Let’s think through the algorithm—that is, the set of steps—that
will turn our one-color spiral into a four-color spiral. Most of the
steps are the same as in our previous spiral programs, but there
are a few added twists:


  1. Import the turtle module and set up a turtle.

  2. Tell the computer which colors we’d like to use.

  3. Set up a loop to draw 100 lines in our spiral.

  4. Pick a different pen color for each side of the spiral.

  5. Move the turtle forward to draw each side.

  6. Turn the turtle left to get ready to draw the next side.
    First, we need a list of color names instead of a single color, so
    we’re going to set up a list variable called colors and put four colors
    in the list, like this:


colors = ["red", "yellow", "blue", "green"]

This list of four colors will give us one
color for each side of our square. Notice we
put the list of colors inside square brackets,
[ and ]. Make sure that each color name
is inside quote marks just like the words
we printed out in Chapter 1, because these
color names are strings, or text values,
that we will pass to the pencolor function
shortly. As noted, we’re using a variable
called colors to store our list of four colors,
so whenever we want to get a color from the
list, we’ll use the colors variable to stand for
the color of the pen. Remember, variables
store values that change. It’s right in their
name: they vary!
Free download pdf