Numbers and Variables: Python Does the Math 47
function asked the user for a string, turtle.numinput() allows the
user to enter a number.
We’ll use this numinput() function to ask the user for the number
of sides (between 1 and 8), and we’ll give the user a default choice of
4 , meaning that if the user doesn’t enter a number, the program will
automatically use 4 as the number of sides. Type the following code
into a new window and save it as ColorSpiralInput.py.
ColorSpiralInput.py
import turtle # Set up turtle graphics
t = turtle.Pen()
turtle.bgcolor("black")
Set up a list of any 8 valid Python color names
colors = ["red", "yellow", "blue", "green", "orange", "purple", "white", "gray"]
Ask the user for the number of sides, between 1 and 8, with a default of 4
sides = int(turtle.numinput("Number of sides",
"How many sides do you want (1-8)?", 4, 1, 8))
Draw a colorful spiral with the user-specified number of sides
for x in range(360):
u t.pencolor(colors[x % sides]) # Only use the right number of colors
v t.forward(x 3 / sides + x) # Change the size to match number of sides
w t.left(360 / sides + 1) # Turn 360 degrees / number of sides, plus 1
x t.width(x sides / 200) # Make the pen larger as it goes outward
This program uses the number of sides the user entered to do
some calculations every time it draws a new side. Let’s look at the
four numbered lines inside the for loop.
At u, the program changes the turtle’s pen color, matching
the number of colors to the number of sides (triangles use three
colors for the three sides, squares use four colors, and so on). At v,
we change the lengths of each line based on the number of sides
(so that triangles aren’t too much smaller than octagons on our
screen).
At w, we turn the turtle by the correct number of degrees.
To get this number, we divide 360 by the number of sides, which
gives us the exterior angle, or the angle we need to turn to draw a
regular shape with that number of sides. For example, a circle is
360 degrees with one “side”; a square is made up of four 90-degree
angles (also 360 degrees total); you need six 60-degree turns to go
around a hexagon (also 360 degrees total); and so on.