Tutorpip← About this lessonOpen the sheet →Download PDF
Ages 10+ · Coding · Python
Functions
def writes it• def cheer():•   spin•   clap•   bowA call runs it• cheer()• Bo spins, claps and bows
Write it once, use it anywhere.
The big ideaA function is a named bundle of lines. Def writes it, and a call runs it.

How it works

A function is a bundle of lines with a name. Write it once, and use it anywhere.

Def writes the function down, but it does not run it. The lines pushed in under def belong to the function.

A call runs the function by its name, on a line of its own that is not pushed in.

A parameter is a blank in the brackets that you fill in each time you call.

def writes therecipeNothing happensyetA call runs itThe linesinside run
Def, then call.

Example 1: Writing a function

  1. Mina types def cheer(): and pushes spin, clap and bow in under it.
  2. That writes the recipe down, like a card with a name on top and steps below.
  3. Bo does nothing yet, because def only writes the recipe.

Example 2: Calling it

  1. Mina writes cheer() on a line of its own.
  2. That is a call, and it runs the function by its name.
  3. Bo spins, claps and bows, from one short line.

Example 3: One fix

  1. At the show, Mina calls cheer at the start, the middle and the end.
  2. That is three calls, so there are three cheers.
  3. She makes the bow deeper once, inside cheer, and all three cheers change.

Example 4: A parameter

  1. Mina writes def greet(name): with a blank called name.
  2. The call greet("Bo") says hi Bo.
  3. The call greet("Teo") says hi Teo, from the very same recipe.

Words to know

function
A named bundle of lines.
def
The word that writes a function down.
call
A line that runs a function by its name.
parameter
A blank in the brackets that the call fills in.

Watch out

Try it

  1. A program has def dance(): with three moves under it, and no other lines. Does Bo dance?
  2. Which makes the function run: def or a call?
  3. The line cheer() is written three times after def cheer():. How many cheers does Bo do?
  4. The function greet has a blank called name. What does greet("Teo") say?
  5. What is the blank in the brackets called?
Answers: 1. No · 2. A call · 3. Three · 4. hi Teo · 5. A parameter
Try at homeBe a function! Ask a grown-up to pick a name for a small routine, like tidy up, which means put away three things. Writing the name down is def. Saying it out loud is a call, and you do the routine, and each time it is said again, you do it again.
For grown-upsBe a function together: pick a name for a small routine, like tidy up, meaning put away three things. Writing the name down is def, saying it aloud is a call, and each call is another go.
Open these notes on screenScan the code, or go to tutorpip.com.