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

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

o ne Variable to rule Them all


So far, we’ve used variables to change the color, size, and turning
angle of our spiral shapes. Let’s add another variable, sides, to rep-
resent the number of sides in a shape. How will this new variable
change our spiral? To find out, try this program, ColorSpiral.py.

ColorSpiral.py

import turtle
t = turtle.Pen()
turtle.bgcolor("black")
# You can choose between 2 and 6 sides for some cool shapes!
sides = 6
colors = ["red", "yellow", "blue", "orange", "green", "purple"]
for x in range(360):
t.pencolor(colors[x%sides])
t.forward(x * 3/sides + x)
t.left(360/sides + 1)
t.width(x*sides/200)

You can change the value of sides from 6 down to 2 (one
side’s not very interesting, and you won’t be able to use bigger
numbers unless you add more colors to the list in the sixth line of
the program). Then save and run the program as many times as
you’d like. Figure 2-8 shows the pictures created with sides = 6 ,
sides = 5 , all the way down to sides = 2, which is the weird, flat
spiral shown in Figure 2-8(e). You can change the order of the
colors in the list, and you can use bigger or smaller numbers in
any of the functions in the drawing loop. If you break the program,
just go back to the original ColorSpiral.py and play some more.
The ColorSpiral.py program uses one new command, t.width();
this changes the width of the turtle’s pen. In our program, the
pen gets wider (its lines get thicker) as it draws larger and larger
shapes. We’ll revisit this program and others like it in Chapters 3
and 4 as you learn the skills needed to create programs like this
from scratch.
Free download pdf