Building Your Own Modules - Teach Your Kids to Code: A Parent-Friendly Guide to Python Programming (2015)

Teach Your Kids to Code: A Parent-Friendly Guide to Python Programming (2015)

Appendix C. Building Your Own Modules

Throughout this book, you’ve imported modules like turtle, random, and pygame into your programs to add functions for drawing, generating a random number, and animating graphics without having to code them from scratch. But did you know that you can also write your own modules and import them into your programs? Python makes it easy to build modules so you can save useful code and use it in many programs.

To create a reusable module, we write the module in IDLE’s file editor window just like other program files we’ve built, and we save it as a new .py file with the name of the module as the filename (for example, colorspiral.py might be the filename for a module that draws color spirals). We define functions and variables in our module. Then, to reuse them in another program, we import the module into the program by typing import and the name of the module (for example, import colorspiral would let a program use the code in colorspiral.py to draw color spirals).

To practice writing our own module, let’s create an actual colorspiral module and see how it saves us from having to rewrite code.

Building the colorspiral Module

Let’s create a colorspiral module to help us draw spirals quickly and easily in our programs just by calling import colorspiral. Type the following code into a new IDLE window and save it as colorspiral.py.

colorspiral.py

➊ """A module for drawing colorful spirals of up to 6 sides"""

import turtle

➋ def cspiral(sides=6, size=360, x=0, y=0):

➌ """Draws a colorful spiral on a black background.

Arguments:

sides -- the number of sides in the spiral (default 6)

size -- the length of the last side (default 360)

x, y -- the location of the spiral, from the center of the screen

"""

t=turtle.Pen()

t.speed(0)

t.penup()

t.setpos(x,y)

t.pendown()

turtle.bgcolor("black")

colors=["red", "yellow", "blue", "orange", "green", "purple"]

for n in range(size):

t.pencolor(colors[n%sides])

t.forward(n * 3/sides + n)

t.left(360/sides + 1)

t.width(n*sides/100)

This module imports the turtle module and defines a function called cspiral() for drawing colorful spirals of different shapes, sizes, and locations. Let’s look at differences between this module and the other programs we’ve written. First, at ➊, we have a special comment called a docstring. A docstring is a way of adding documentation to files that we intend to reuse or share with others; in Python, modules should have docstrings to help future users understand what the module does. The docstring will always be the first statement in a module or function, and each docstring starts and ends with triple double quotes (""", three double quotes in a row with no spaces in between). After the docstring, we import the turtle module — yes, we can import modules into our modules!

At ➋, we define a function called cspiral() that accepts up to four arguments — sides, size, x, and y — for the number of sides in the spiral, the size of the spiral, and the (x, y) location of the spiral starting from the center of the turtle screen. A docstring for the cspiral() function begins at ➌; this multiline docstring provides more specific information about the function. The first line of the docstring begins with triple double quotes and describes the function overall. Next we leave a blank line, followed by a list of the arguments accepted by the function. With this documentation, a future user can easily read which arguments are accepted by the function and what each one means. The rest of the function is the code to draw a colorful spiral, similar to code from Chapter 2, Chapter 4, and Chapter 7.

Using The Colorspiral Module

Once we’ve completed colorspiral.py and saved it, we can use it as a module by importing it into another program. Create a new file in IDLE and save it as MultiSpiral.py in the same folder as colorspiral.py.

MultiSpiral.py

import colorspiral

colorspiral.cspiral(5,50)

colorspiral.cspiral(4,50,100,100)

This three-line program imports the colorspiral module we created and uses the module’s cspiral() function to draw two spirals on the screen, as shown in Figure C-1.

Two colorful spirals created with a three-line program, thanks to the colorspiral.py module

Figure C-1. Two colorful spirals created with a three-line program, thanks to the colorspiral.py module

With the colorspiral module, anytime a programmer wants to create colorful spirals, all they have to do is import the module and call colorspiral.cspiral()!

Reusing the Colorspiral Module

Let’s reuse the colorspiral module to draw 30 random, colorful spirals. To do that, we’ll import another module we’ve used before, random. Type the following eight lines of code into a new file in IDLE and save the file as SuperSpiral.py.

SuperSpiral.py

import colorspiral

import random

for n in range(30):

sides = random.randint(3,6)

size = random.randint(25,75)

x = random.randint(-300,300)

y = random.randint(-300,300)

colorspiral.cspiral(sides, size, x, y)

This program begins with two import statements: one for the colorspiral module we created and the other for the random module we’ve used throughout the book. The for loop will run 30 times. The loop generates four random values for the number of sides (between 3 and 6), the size of the spiral (between 25 and 75), and the x- and y-coordinates to draw the spiral on the screen, between (–300, –300) and (300, 300). (Remember that the turtle’s origin, (0, 0), is at the center of the drawing screen.) Finally, each pass through the loop calls the colorspiral.cspiral() function from our module, drawing a colorful spiral with the randomly generated attributes from the loop.

Although this program is only eight lines long, it produces stunning graphics like Figure C-2.

The colorspiral module allows SuperSpiral.py to produce a lovely multispiral collage with only eight lines of code.

Figure C-2. The colorspiral module allows SuperSpiral.py to produce a lovely multispiral collage with only eight lines of code.

The ability to create reusable modules means that you can spend more time solving new problems and less time recoding previous solutions. Whenever you build a useful function or set of functions that you want to use over and over, you can create a module to use for yourself or share with fellow coders.

Additional Resources

The official documentation for Python at http://docs.python.org/3/ includes more information on modules and the Python language. The Python Tutorial has a section on modules at http://docs.python.org/3/tutorial/modules.html. As you learn new Python programming skills, make use of these resources to add to your coding tool set.