142 Chapter 7
Functions are helpful because they give us the ability to orga-
nize pieces of reusable code, then refer to those pieces later in our
programs by a single short name or command. Take input() as
an example: it prints a text prompt to ask a user for input, col-
lects what the user types, and passes it to our program as a string
that we can store in a variable. We reuse the input() function any-
time we want to know something more from the user. If we didn’t
have this function, we might have to do all that work ourselves
every time we wanted to ask the user for information.
The turtle.forward() function is
another great visual example: every
time we move the turtle forward to
draw one of the sides of our spirals,
Python draws one pixel at a time
in the direction our turtle is cur-
rently heading on the screen, to the
exact length we ask for. If we didn’t
have the turtle.forward() function,
we would have to figure out how to
color pixels on the screen, keep track
of locations and angles, and do some
fairly complex math to draw a cer-
tain distance every time.
Without these functions, our programs would be longer, harder
to read, and harder to write. Functions let us take advantage of
the previous programming work of lots of fellow coders. The good
news is that we can also write our own functions to make our code
shorter, easier to read, and more reusable.
In Chapter 6, we built programs that drew random spirals and
a kaleidoscope pattern. We can use functions to make the code in
these programs easier to read and to make parts of the code more
reusable.
Putting Things Together with Functions
Look back at RandomSpirals.py on page 115. Everything in the
first for loop is the code to create just one random spiral. The for
loop uses that code to draw 50 spirals of random color, size, and
location.