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

(vip2019) #1

60 Chapter 4


360 degrees by that number, and we’ll find the number of degrees
to turn left each pass through the loop. Type and run the following
code as RosetteGoneWild.py:

RosetteGoneWild.py

import turtle
t = turtle.Pen()


Ask the user for the number of circles in their rosette, default to 6


u number_of_circles = int(turtle.numinput("Number of circles",
"How many circles in your rosette?", 6))
v for x in range(number_of_circles):
w t.circle(100)
x t.left(360/number_of_circles)


At u, we assign a variable called number_of_circles using a
couple of functions together. We’re using Turtle’s numinput() func-
tion to ask the user how many circles to draw. The first value,
Number of circles, is the pop-up window’s title; the second, How many
circles in your rosette?, is the text that will appear in the box;
and the last, 6 , is a default value in case the user doesn’t enter
anything. The int() function outside numinput() turns the user’s
number into an integer we can use
in our range() function. We store the
user’s number as number_of_circles to
use as the size of the range() in our
drawing loop.
The for statement at v is our loop.
It uses the number_of_circles variable to
loop x through a list of that many num-
bers. The command to draw a circle
is still the same at w and will draw
circles with a radius of 100 pixels.
At x, we’re dividing a full turn of
360 degrees by the number of circles so
we can draw the circles evenly spaced
around the center of the screen. For
example, if the user enters 30 as the
number of circles, 360 ÷ 30 would give
us a 12-degree turn between each of
the 30 circles around our center point,
as shown in Figure 4-3.
Free download pdf