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

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

Here’s the whole program together; type this into IDLE and
save it as RandomSpiralsFunction.py or download it from h t t p : //
http://www.nostarch.com/teachkids/.

RandomSpiralsFunction.py

import random
import turtle
t = turtle.Pen()
t.speed(0)
turtle.bgcolor("black")
colors = ["red", "yellow", "blue", "green", "orange", "purple",
"white", "gray"]
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)

for n in range(50):
random_spiral()

In addition to a more readable program, we also get a reusable
random_spiral() function that we can copy, modify, and easily use in
other programs.
If you find yourself reusing a chunk of code again and again,
convert it into a function like we did with random_spiral() using def,
and you’ll find it much easier to port the code—that is, carry it
over and reuse it—into new applications.

n ote You can even create your own module full of
functions and import your module just like
we’ve imported turtle and random in our pro-
grams (see Appendix C on how to create a
module in Python). That way you can share
your code with friends.

Free download pdf