Functions & return · About 10 minutes

Invent your own superpower

The big little idea

A function is a reusable recipe. Define it with def, give it a name, and call it whenever you need that recipe. Parameters let the recipe work with different ingredients.

def double(number):
    return number * 2

print(double(6))

return sends a value back to the place where the function was called. It is different from print(): return gives the result to your code, while print() displays it to the person running the program.

Predict, then try: read the example from top to bottom. What do you think it will print? Copy it into the editor below to test your prediction.

Your turn, code explorer.

Write a triple function that returns a number multiplied by 3. Calling triple(7) should print 21.

21
my_adventure.pyPython · in your browser

Edit the code. Then run it. Ctrl / ⌘ + Enter also works.

OutputYOUR IDEAS, ALIVE
Your program’s output will appear here.

Ready when you are. ✦

The first run loads Python. This can take a moment.

Program input For programs that use input()

Add answers before you run. Each input() reads the next line. Use made-up names and details.

Real Python, powered by Pyodide. Standard-library programs work here; desktop windows, turtle graphics, and package installation are not supported by this editor. Programs stop after 10 seconds of execution.

Back to the starting code?

This replaces your edits for this activity. Download your code first if you want to keep it.

A little hint, please

Change the return line to return number * 3. Keep it indented.

Show one possible solution

There can be more than one way. Read this version, then try writing it yourself.

def triple(number):
    return number * 3

print(triple(7))
Pack this idea for later: Functions help you organize a program and reuse an idea.