The juicer
Oranges go in. Juice comes out, and you can drink it.
07FUNCTIONS ยท RETURN
Some boxes do more than a job: they hand you a result. You send something in, it works inside, and return sends something out.
IN REAL LIFE
Many machines at home give you something back.
Oranges go in. Juice comes out, and you can drink it.
Bread goes in. Toast comes back to you.
2 + 3 goes in. 5 comes back, and you can use it again.
LOOK AT THE BOX
def double(number): makes a box called double.
What goes between the parentheses is a parameter. double(4) sends 4 into the box.
return is the box's exit door. The result comes out through it.
From outside, you only need to know what goes in and what comes out.
OPEN THE BOX
Look inside two boxes. Every line is something you already learned.
def check_battery(battery):battery is a variable box. It gets filled when you call. if battery < 30:An if, like in Choose a path. plan = "charge"A variable box, like in Memory boxes. else:The other path. plan = "play"A variable box, like in Memory boxes. return planreturn sends the result out of the box.def beep(times):times is a variable box. It gets filled when you call. for turn in range(times):A loop, like in Repeat a pattern. print("beep")The small job that repeats. return "done"return sends the result out of the box.The secret: A function is just variables and instructions you already know, packed in a box with a name.
RUN IT
Guess first. Then run real Python and check.
def double(number):
answer = number + number
return answer
print(double(4))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 4 to 10. What comes out of the box now?
YOUR TURN
Try each tiny question. A wrong answer becomes something to review.
def greet(name):Which word is the parameter?
def add_one(n):
return n + 1
add_one(5)What does the box give back?
What can it find inside?
def triple(n):
return n * 3What is this box called?
def double(number):
return number + number
print(double(10))What will Python show?
In a function, what is the juice?
The box forgot its exit door. Make 10 come out.
10OUTPUT
Want a fresh start? Clear only this page.
Everything inside the box is something you already know. Next: boxes that already come with every value. They are called methods.