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

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

Run the program and try your own numbers. You can even
make a rosette of 90 circles, or 200 (but you’ll be waiting a while
as Python draws that many circles!). Customize the program to
make it your own: change the background color or the rosette
color, make the circles bigger or smaller, or make them bigger and
smaller! Play with your programs as you create them and as you
think of fun things you’d like them to do. Figure 4-4 shows what
my five-year-old son, Alex, dreamed up by adding just three extra
lines of code to RosetteGoneWild.py. Go to http://www.nostarch
.com/teachkids/ for the source code.

Game Loops and while Loops


The for loop is powerful, but there are limits to its power. For
instance, what if we wanted to stop our loop when some event
occurred, instead of going all the way through a long list of num-
bers? Or what if we weren’t sure how many times to run our loop?
For example, consider a game loop—when we write a pro-
gram, especially a game, where the user gets to choose whether
to keep playing or to quit. We, as programmers, can’t know in
advance how many times users will choose to play our game or

Figure 4-3: A user-defined rosette of
30 circles


Figure 4-4: A little imagination and a touch
of code can turn our rosette program into a
lot of colorful fun!
Free download pdf