Bottle a useful idea.
Write a function once and give it a clear job to do many times.
01 The idea
A function groups behaviour behind a name. Define it with def, give it parameters for the values it needs, and use return to send a result back. A useful function has a focused responsibility and does not require its caller to know every implementation detail.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
def remaining_tasks(total, completed):
"""Return how many tasks are still open."""
return total - completed
open_tasks = remaining_tasks(12, 5)
print(open_tasks)7
03 Under the hood
- 1
The definition creates the function; it does not run the body immediately. The call provides arguments 12 and 5.
- 2
Within the call, total and completed are local parameter names. return evaluates the result and ends that function call.
- 3
The docstring explains the purpose. Keep returning a value separate from displaying it so the function can be reused in a web app, a test, or another calculation.
04 Your turn, builder
Write a double(number) function that returns twice its input, then print double(9).
Reveal one possible solution +
def double(number):
return number * 2
print(double(9))05 Check your signal
What does a function without an explicit return produce?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.