←Previous page

07FUNCTIONS · DEF

Teach PyBot a trick.

A function is a box with a name that keeps some steps inside. Write the steps once with def. Then call the name any time, and the box does its job.

IN REAL LIFE

One name for many steps.

You already do this. One short name, and you know every step of the job.

Brush your teeth

One name, many steps: wet the brush, add paste, brush, rinse.

Sing happy birthday

Same song, a new name each time. The name is what you send in.

Wave hello

You just do it. Nothing comes back to you. That is a box that only does a job.

LOOK FIRST

Make the box, then call it.

def makes the box

def say_hi(): gives the box a name. The steps go below, moved to the right.

Call it by name

say_hi() runs every step in the box. Call it again, and it runs again.

Send something in

def greet(name): has a parameter. greet("Ana") puts Ana in the name box.

STEP BY STEP

PyBot learns, then PyBot does.

Follow Python from the top. Learning the trick shows nothing. Calling it does the job.

def greet(name):PyBot learns a trick called greet. Nothing shows yet.
print("Hi", name)The job, inside the box. It is moved to the right.
greet("Ana")Call! name gets Ana. Python shows: Hi Ana
greet("Leo")Call again! name gets Leo. Python shows: Hi Leo

RUN IT

Teach PyBot to clap.

Guess first. Then run real Python and check.

1

Guess the result

def clap(times): for turn in range(times): print("clap") clap(3)

What will Python show?

clap.pyREAL PYTHON
OUTPUT
Ready. Press Run Python.
Python runs here thanks to Pyodide ♥

Pyodide 314.0.3 runs CPython in your browser with WebAssembly.

Open-source under the Mozilla Public License 2.0. License

Now change one thing: Change 3 to 5. Then add one more line at the end: clap(1).

YOUR TURN

Learn a trick, then use it.

Try each tiny question. A wrong answer becomes something to review.

0Completed
9Not tried
0Review
01

Get ready!

Every morning Dad says: get ready! PyBot washes, gets dressed and eats breakfast.

What is “get ready” like in Python?

02

The magic word

Which word makes a new function?

03

Only learned

def wave(): print("hi!")

What does Python show?

04

Use the trick

PyBot made a box with def wave():

Which line makes the box do its job?

05

Call it twice

def beep(): print("beep") beep() beep()

How many beeps show?

06

Send in a name

def greet(name): print("Hi", name) greet("Leo")

What does Python show?

07

Inside or outside?

def wave(): print("hi") print("bye")

Which line is inside the box?

08

Fix PyBot's code

PyBot learned a trick but never used it. Make it show: Hi Ana

Goal output
Hi Ana
OUTPUT

Your work is saved here.

Want a fresh start? Clear only this page.

!
BIG IDEA

def teaches a trick. A call does it.

These boxes do a job and give nothing back. Next: boxes that give you something back with return.