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

(vip2019) #1

66 Chapter 4


Ask for the first name


v name = turtle.textinput("My family",
"Enter a name, or just hit [ENTER] to end:")


Keep asking for names


w while name != "":


Add their name to the family list


x family.append(name)


Ask for another name, or end


name = turtle.textinput("My family",
"Enter a name, or just hit [ENTER] to end:")


Draw a spiral of the names on the screen


for x in range(100):
y t.pencolor(colors[x%len(family)]) # Rotate through the colors
z t.penup() # Don't draw the regular spiral lines
{ t.forward(x*4) # Just move the turtle on the screen
| t.pendown() # Draw the next family member's name
} t.write(family[x%len(family)], font = ("Arial", int((x+4)/4), "bold") )
~ t.left(360/len(family) + 2) # Turn left for our spiral


At u, we set up an empty list [] called family that will hold
the names the user enters. At v, we ask for the first name in a
turtle.textinput window and start the while loop to gather all the
names in the family at w. The command to add a value to the
end of a list is append(), shown at x. This takes the name the user
entered and appends it to the list called family. We then ask for
another name and keep repeating the while loop w until the user
presses enter to let us know they’re finished.
Our for loop starts out like previous spirals, but we use a new
command at y to set our pen color. The len() command is short for
length and tells us the length of the list of names stored in family.
For example, if you entered four names for your family, len(family)
would return 4. We use the modulo operator, %, with this value
to rotate through four colors, one for each name in family. Larger
families would rotate through more colors (up to the 10 colors in
our list), while smaller families would need fewer colors.
At z, we use the penup() command to “lift” the turtle’s pen
off the screen so that when we move forward at {, the turtle won’t
draw anything; we’ll be drawing names at the corners of the spi-
ral, with no lines in between. At |, we put the turtle’s pen down
again so that our names will be drawn.
At }, we’re doing a lot. First, we tell the turtle which name to
draw. Notice that family[x%len(family)] uses the modulo operator, %,
Free download pdf