Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Build your toolkit
EXPERIMENT 15 / 101

Bottle a useful idea.

Write a function once and give it a clear job to do many times.

BY NAVAN SAMI◷ 6 MIN READPYTHON 3

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.

functions.py
def remaining_tasks(total, completed):
    """Return how many tasks are still open."""
    return total - completed

open_tasks = remaining_tasks(12, 5)
print(open_tasks)
↳ EXPECTED OUTPUT
7

03 Under the hood

  1. 1

    The definition creates the function; it does not run the body immediately. The call provides arguments 12 and 5.

  2. 2

    Within the call, total and completed are local parameter names. return evaluates the result and ends that function call.

  3. 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

A SMALL MISSION

Write a double(number) function that returns twice its input, then print double(9).

Reveal one possible solution +
one_possible_solution.py
def double(number):
    return number * 2

print(double(9))

05 Check your signal

QUICK SIGNAL CHECK

What does a function without an explicit return produce?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

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 ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.