Brush your teeth
One name, many steps: wet the brush, add paste, brush, rinse.
07FUNCTIONS · DEF
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
You already do this. One short name, and you know every step of the job.
One name, many steps: wet the brush, add paste, brush, rinse.
Same song, a new name each time. The name is what you send in.
You just do it. Nothing comes back to you. That is a box that only does a job.
LOOK FIRST
def say_hi(): gives the box a name. The steps go below, moved to the right.
say_hi() runs every step in the box. Call it again, and it runs again.
def greet(name): has a parameter. greet("Ana") puts Ana in the name box.
STEP BY STEP
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 Anagreet("Leo")Call again! name gets Leo. Python shows: Hi LeoRUN IT
Guess first. Then run real Python and check.
def clap(times):
for turn in range(times):
print("clap")
clap(3)What will Python show?
PyBot's hint
Ready. Press Run Python.
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
Try each tiny question. A wrong answer becomes something to review.
What is “get ready” like in Python?
Which word makes a new function?
def wave():
print("hi!")What does Python show?
Which line makes the box do its job?
def beep():
print("beep")
beep()
beep()How many beeps show?
def greet(name):
print("Hi", name)
greet("Leo")What does Python show?
def wave():
print("hi")
print("bye")Which line is inside the box?
PyBot learned a trick but never used it. Make it show: Hi Ana
Hi AnaOUTPUT
Want a fresh start? Clear only this page.
These boxes do a job and give nothing back. Next: boxes that give you something back with return.