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

(vip2019) #1

58 Chapter 4


Modifying our for Loop to Make
a rosette with six Circles
Now that we’ve built our own for
loop together from scratch, could
you modify the program on your
own to draw something new? What
if we wanted to draw a rosette with
six circles instead of four? What
might we need to change in our
program? Take a moment to think
about how you might solve this
problem.

  

Did you come up with some
ideas? Let’s walk through the prob-
lem together. First, we know that
we need six circles this time instead
of four, so our range will need to
change to range(6) in our for loop. But if we just change that, we’re
not going to see any difference in our drawing, because we’ll con-
tinue to draw over the same four circles separated by 90 degrees.
If we want six circles around the rosette, we’ll need to divide the
rosette into six left turns instead of four. There are 360 degrees
around the center of our drawing: four 90-degree turns took us
4 × 90 = 360 degrees all the way around. If we divide 360 by 6
instead of 4, we get 360 ÷ 6 = 60 degrees for each turn. So in
our t.left() command, we need to turn left 60 degrees each time
through the loop, or t.left(60).
Modify your rosette program and save it as Rosette6.py.
Rosette6.py

import turtle
t = turtle.Pen()
u for x in range( 6 ):
v t.circle(100)
w t.left( 60 )

This time, the for loop statement in u will step x through the
list of six values from 0 to 5 , so we’ll repeat the indented steps v
Free download pdf