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

(vip2019) #1
Loops Are Fun (You Can Say That Again) 69

import turtle
t = turtle.Pen()
u t.penup()
turtle.bgcolor("black")


The first few lines of our program look like the other spirals
we’ve programmed, except that we won’t be drawing lines for the
big spiral. We plan to replace those with smaller spirals, so we
have a t.penup() at u to lift the turtle’s pen off the screen right
from the beginning. We then set the background color to black.
Keep typing: we’re not done! Next we’ll ask the user for the
number of sides they want using turtle.numinput(), with a default
of 4 if the user doesn’t choose something different, and we’ll restrict
the range of allowable sides to between 2 and 6.

sides = int(turtle.numinput("Number of sides",
"How many sides in your spiral of spirals (2-6)?", 4,2,6))
colors = ["red", "yellow", "blue", "green", "purple", "orange"]

The turtle.numinput() function allows us to specify a title for
our input dialog; a prompt question; and default, minimum, and
maximum values, in that order: turtle.numinput(title, prompt,
default, minimum, maximum). Here, we specify a default value of 4 , a
minimum of 2 , and a maximum of 6. (If the user tries to enter 1
or 7 , for example, they’ll get a warning that the minimum allowed
value is 2 and the maximum allowed value is 6 .) We also set up our
colors list with six colors.
Next we’ll write our outer spiral loop. The outer loop will posi-
tion the turtle at each corner of the big spiral.

v for m in range(100):
t.forward(m*4)
w position = t.position() # Remember this corner of the spiral
x heading = t.heading() # Remember the direction we were heading


Our outer loop takes m from 0 to 99 for 100 total passes v. In
our outer loop, we move forward just like in our other spiral pro-
grams, but when we reach each corner of our big spiral, we stop to
remember our position w and heading x. The position is the turtle’s
(x, y) coordinate location on the screen, and the heading is the
direction the turtle is moving in.
Our turtle is taking a bit of a detour at every spot along the
large spiral in order to draw the smaller spirals, so it must return
Free download pdf