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

(vip2019) #1

144 Chapter 7


on the screen, and then move the pen there and draw the spiral.
Here’s the code to complete our random_spiral() function:

def random_spiral():
t.pencolor(random.choice(colors))
size = random.randint(10,40)
x = random.randrange(-turtle.window_width()//2,
turtle.window_width()//2)
y = random.randrange(-turtle.window_height()//2,
turtle.window_height()//2)
t.penup()
t.setpos(x,y)
t.pendown()
for m in range(size):
t.forward(m*2)
t.left(91)

Note that the computer doesn’t actually run the code when the
function is being defined. If we type the function definition into
IDLE, we won’t get a spiral—yet. To actually draw a spiral, we
need to call the random_spiral() function.

Calling random_spiral()


A function definition tells the computer what we want to do when
someone actually calls the function. After defining a function,
we call it in our program using the function’s name followed by
parentheses:

random_spiral()

You’ve got to remember the parentheses, because that tells the
computer you want to run the function. Now that we’ve defined
random_spiral() as a function, when we call random_spiral() like this
in our program, we’ll get a random spiral drawn on a turtle screen.
Now, to draw 50 random spirals, instead of using all the code
in RandomSpirals.py, we can shorten our for loop to this:

for n in range(50):
random_spiral()

This loop is easier to read, thanks to our use of a function that
we built all by ourselves. We’ve made our code easier to understand,
and we can easily move the random spiral code over into another
program by copying and pasting the function definition.
Free download pdf