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

(vip2019) #1

68 Chapter 4


p tting u it All Together:


spiral goes Viral


We’ve seen the power of loops: they take pieces of code and repeat
them over and over to do repetitive work that we wouldn’t want
to do by hand, like typing a name 100 times. Let’s take loops one
step further and build our own nested loop, which is a loop inside
another loop (like Russian nesting dolls—look inside one doll, and
there’s another doll).

To explore nested loops, let’s draw a spiral not of names or
lines but of spirals! Instead of drawing a name at every corner of
our spiral like we did in Figure 4-6, we could draw a smaller spi-
ral. To accomplish that, we need a big loop to draw a big spiral on
the screen and a little loop inside to draw small spirals around the
big spiral.
Before we write a program to do that, let’s learn how to nest a
loop inside another loop. First, start a loop as usual. Then, inside
that loop, press tab once and start a second loop:

# This is our first loop, called the outer loop
for x in range(10):
# Things indented once will be done 10 times
# Next is our inner loop, or the nested loop
for y in range(10):
# Things indented twice will be done 100 (10*10) times!

The first loop is called the outer loop, because it surrounds our
nested loop. The nested loop is called the inner loop, because it sits
inside the other loop. Notice that in our nested loop, any lines of code
that are indented twice (so they’re inside the second loop) will be
repeated 10 times for y and 10 times for x, or 100 times total.
Let’s start writing our program, ViralSpiral.py. We’ll write it
step by step—the finished program is shown on page 72.
Free download pdf