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

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

This code works, but doesn’t it feel repetitive? We typed the
code to draw a circle four times and the code to turn left three
times. We know from our spiral examples that we should be able to
write a chunk of code once and reuse that code in a for loop. In this
chapter, we’re going to learn how to write those loops ourselves.
Let’s try it now!

Building Your Own for Loops


To build our own loop, we first need to identify the repeated steps.
The instructions that we’re repeating in the preceding code are
t.circle(100) to draw a turtle circle with a radius of 100 pixels and
t.left(90) to turn the turtle left 90 degrees before drawing the next
circle. Second, we need to figure out how
many times to repeat those steps. We
want four circles, so let’s start with four.
Now that we know the two repeated
instructions and the number of times
to draw the circle, it’s time to build our
for loop.
A for loop in Python iterates over
a list of items, or repeats once for each
item in a list—like the numbers 1
through 100, or 0 through 9. We want
our loop to run four times—once for
each circle—so we need to set up a list
of four numbers.
The built-in function range() allows us to easily create lists of
numbers. The simplest command to construct a range of n num-
bers is range(n); this command will let us build a list of n numbers
from 0 to n – 1 (from zero to one less than our number n).
For example, range(10) allows us to create a list of the 10 num-
bers from 0 to 9. Let’s enter a few sample range() commands in the
IDLE command prompt window to see how this works. To see our
lists printed out, we’ll need to use the list() function around our
range. At the >>> prompt, enter this line of code:

>>> list(range(10))

IDLE will give you the output [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]: a
list of 10 numbers, starting from 0. To get longer or shorter lists of
Free download pdf