Functions: write a recipe once, use it anywhere
A baker doesn't invent brownies from scratch every morning. They follow a recipe. A function is a recipe for your code: steps you write once and run by name.
The big idea
def writes a function, a named recipe of steps. Calling the name, with parentheses, runs those steps.
See it in code
def starts the recipe and gives it a name. The pushed-in lines are its steps. Nothing happens until the last line calls it:
def open_shop():
print("=== ELECTRIC BAKERY ===")
print("We're open!")
open_shop()=== ELECTRIC BAKERY === We're open!
The two print lines waited inside the recipe. open_shop() is the call. That's the moment the steps actually ran.
A recipe can be used again and again. Each call runs every step, wherever the call sits in your program:
def ring_bell():
print("Ding ding!")
ring_bell()
print("Order up: cookie")
ring_bell()
print("Order up: brownie")Ding ding! Order up: cookie Ding ding! Order up: brownie
You wrote "Ding ding!" once and heard it twice. Change the recipe and every call changes with it.
A recipe can paint, too. These five shapes make a ladybug, and now they have one name:
def ladybug():
circle(x=200, y=178, size=18, color="black")
circle(x=200, y=200, size=40, color="red")
line(x1=200, y1=180, x2=200, y2=220, color="black", width=2)
circle(x=191, y=200, size=8, color="black")
circle(x=209, y=200, size=8, color="black")
paper("light sky blue")
rect(x=200, y=300, width=400, height=200, color="yellow green")
oval(x=200, y=205, width=110, height=56, color="forest green")
ladybug()
The last line is short and easy to read. It says what the program paints, and the recipe above holds the details.
Big programs are mostly recipes. A game has one for starting over and one for making the next wave. A shop has one for printing a receipt.
Try it yourself
Add a second ladybug() call at the bottom and run it. You still see one ladybug. Why? Both calls paint in the very same spot. That puzzle is solved by giving a recipe inputs.
The common mistake
Writing a recipe and never calling it. def only writes the steps down. If nothing appears when you run your program, check that the call is there.
What it unlocks
A recipe gets far more useful when you can give it inputs, so each call does something a little different. After that, learn how a recipe can hand an answer back.