Functions: teach the computer a new command
A function lets you teach the computer a brand-new command. Bundle a few steps under one name, then run all of them by calling that name.
The big idea
A function gives a group of steps one name. Then you run them all with a single line.
See it in code
A function bundles a few steps under one name. def cheer(): names the steps, and everything indented under it is the recipe. Nothing happens until you call it by name:
def cheer():
print("Great job!")
print("Take a badge!")
cheer()Great job! Take a badge!
The two print lines got one name, cheer. Writing cheer() runs them both.
The magic is reuse. Write the recipe once, then call it as many times as you like — each call runs the whole thing again:
def cheer():
print("Great job!")
print("Take a badge!")
cheer()
cheer()Great job! Take a badge! Great job! Take a badge!
Two calls, so the recipe ran twice. You never copied the lines — you reused the one name.
Now in the art studio. A badge is a star sitting above a flower — so we teach a stamp command that draws both. This one takes an x, so each call can land in a different spot:
from art import Canvas, star, flower
screen = Canvas.create()
Canvas.fill(screen)
def stamp(x):
star(screen, x, 200, size=70)
flower(screen, x, 300, size=70)
stamp(150)
stamp(350)
Same idea as cheer, but the recipe draws a badge. We wrote it once, then stamped it twice. Want ten badges? Ten short stamp(...) calls — no recipe copying.
Functions are useful everywhere. draw_house(), roll_dice(), greet_player() — any time you would copy the same steps, wrap them in a function instead. Write it once. Fix bugs in one place. Reuse it forever.
Try it yourself
Add a third badge with stamp(250) in the middle. Then change the flower's size to 50 inside the recipe — every badge updates at once, because they all share the one recipe.
The common mistake
Forgetting to call the function. Writing def stamp(x): only teaches the command — it does not run it. Nothing appears until you actually write stamp(150) underneath.
What it unlocks
Functions get their real power from arguments, which change what each call does, and return values, which send an answer back out.