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

(vip2019) #1

290 Appendix C


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 vari-
ables 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

u """A module for drawing colorful spirals of up to 6 sides"""
import turtle
v def cspiral(sides=6, size=360, x=0, y=0):
w """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)
Free download pdf