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

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

difference is that we can’t just print each name one by one; to draw
our spiral, we need to have all the names at once so that we can
draw each name in sequence as we wind around our spiral.
In SayOurNames.py, we were able to ask for one name at a
time, but for our graphical spiral name program, we’ll need to keep
all of the names in a list, just as we do with our colors. Then, as we
go around the loop, we can change the names and colors together
at each corner of the spiral. To do this, we’ll set up an empty list:

family = [] # Set up an empty list for family names

Whenever we’ve made a list of colors in our programs, we’ve
known the color names that we wanted to use, like red, yellow,
blue, and so on. In our family list, though, we have to wait until
the user enters the names. We use an empty list—a pair of square
brackets, []—to let Python know that we’re going to use a list
called family but that we don’t know what will be in the list until
the program runs.
Once we have an empty list, we can
ask for names in a while loop like we did in
SayOurNames.py, and we will append those
names to the list. To append means to add
items to the end of the list. In this program,
the first name the user enters will be added
to the empty list, the second name will be
appended after the first, and so on. When the
user has entered all the names they want in
their spiral, they will press enter to tell the
program that they’ve finished entering names.
Then we’ll use a for loop to draw the names
on the screen in a colorful spiral shape.
Type and run the following code to see
a while loop and a for loop do some beautiful
work together:

SpiralFamily.py

import turtle # Set up turtle graphics
t = turtle.Pen()
turtle.bgcolor("black")
colors = ["red", "yellow", "blue", "green", "orange",
"purple", "white", "brown", "gray", "pink" ]
u family = [] # Set up an empty list for family names

Free download pdf