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

(vip2019) #1
Numbers and Variables: Python Does the Math 45

the power of strings with colorful turtle graphics. Let’s give it a
try! In the following program, we’ll set up turtle graphics just like
in our earlier spirals, but instead of drawing lines or circles on the
screen, we’ll ask the user for their name and then draw it on the
screen in a colorful spiral. Type this into a new window and save it
as SpiralMyName.py.

SpiralMyName.py

# SpiralMyName.py - prints a colorful spiral of the user's name

import turtle # Set up turtle graphics
t = turtle.Pen()
turtle.bgcolor("black")
colors = ["red", "yellow", "blue", "green"]

Ask the user's name using turtle's textinput pop-up window


u your_name = turtle.textinput("Enter your name", "What is your name?")


Draw a spiral of the name on the screen, written 100 times


for x in range(100):
t.pencolor(colors[x%4]) # Rotate through the four colors
v t.penup() # Don't draw the regular spiral lines
w t.forward(x*4) # Just move the turtle on the screen
x t.pendown() # Write the user's name, bigger each time
y t.write(your_name, font = ("Arial", int( (x + 4) / 4), "bold") )
t.left(92) # Turn left, just as in our other spirals


Most of the code in SpiralMyName.py looks just like our earlier
color spirals, but we ask the user their name in a turtle.textinput
pop-up window at u and store the user’s answer in your_name. We’ve
also changed the drawing loop by lifting the turtle’s pen off the
screen at v so when we move the turtle forward at w, it doesn’t
leave a trail or draw the normal spiral line. All we want in the
spiral is the user’s name, so after the turtle moves at w, we tell it
to start drawing again with t.pendown() at x. Then with the write
command at y, we tell the turtle to write your_name on the screen
every time through the loop. The final result is a lovely spiral; my
son Max ran the one shown in Figure 3-8.
Free download pdf