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

(vip2019) #1
Functions: There’s a Name for That 143

Say we want to use that random spiral code in another program,
like a game or a screensaver app. In RandomSpirals.py, it’s not
easy to tell where the actual spiral drawing starts or stops, and we
just wrote that code a few pages ago. Imagine coming back to this
program in three months! We would have a hard time figuring out
what the app is supposed to do and which lines we need to copy over
into a new program if we want to draw random spirals again.
To make a piece of code reusable later, or just easier to read
now, we can define a function and give it an easy-to-understand
name, just like input() or turtle.forward(). Defining a function is
also called declaring the function, and it just means that we’re
telling the computer what we want the function to do. Let’s create
a function to draw a random spiral on the screen; we’ll call it
random_spiral(). We can reuse this function anytime we want to
draw random spirals, in any program.


Defining random_spiral()


Open RandomSpirals.py (Chapter 6), save it as a new file called
RandomSpiralsFunction.py, and begin this function definition
after setting up the turtle’s pen, speed, and colors but before the
for loop. (You can refer to the final program on page 145 to see
how this should look.) Our definition of random_spiral() should
go after the turtle setup because the function will need to use the
turtle pen t and the list of colors. The definition should go before
the for loop because we’ll be using random_spiral() in the for loop,
and you have to define a function before you can use it. Now that
we’ve found the right place in our program, let’s start defining the
random_spiral() function.
We define a function in Python using the keyword def (short for
definition), followed by the name of the function, parentheses (), and
a colon (:). Here’s the first line of the random_spiral() function we’ll
build:


def random_spiral():


The rest of the function definition will be one or more
statements, indented from the left, just like when we grouped
statements in our for loops. To draw a random spiral, we need to
set a random color, a random size, and a random (x, y) location

Free download pdf