Parameters and return
Passing values in, getting results back, and default values.
5 minute read
Big idea
return sends a value back to whoever called the function. Parameters can have default values, and arguments can be passed by name.
return
def square(n):
return n * n
result = square(5)
print(result)
print(square(3) + square(4))output
25
25Run and edit it in the app.
The call square(5) is replaced by the value it returns, so you can store it, print it, or use it in more maths.
return also ends the function immediately — anything after it in that path never runs.
print is not return
This is the most common confusion with functions:
def shout(word):
print(word.upper())
result = shout("hi")
print(result)What does it print? Show the answer
HI
NoneRun and edit it in the app.
shout prints, but it doesn't return anything — and a function with no return gives back None. Return a value when the caller needs to use it; print only when the job is to show something.
def add(a, b):
print(a + b)
total = add(10, 20)
print("Total:", total)output
Total: 30Run and edit it in the app.
Several parameters, and defaults
def power(base, exponent=2):
return base ** exponent
print(power(5))
print(power(2, 10))output
25
1024Run and edit it in the app.
exponent=2 is a default: used when the caller doesn't pass that argument. Parameters with defaults must come after those without.
Keyword arguments
You can pass arguments by name. Then order doesn't matter, and the call explains itself:
def describe(name, age, city):
return f"{name}, {age}, from {city}"
describe("Ada", 36, "London") # by position
describe(city="Paris", name="Marie", age=66) # by name
Returning several values
Return a tuple and unpack it on the other side:
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([7, 2, 9, 4])
print(low, high)output
2 9Run and edit it in the app.
Watch out: a list as a default
Default values are made once, when the def runs. A list default is shared between calls — surprising:
def add_item(item, items=[]): # ✗ the same list every call
items.append(item)
return items
def add_item(item, items=None): # ✓ a fresh list each time
if items is None:
items = []
items.append(item)
return items
What does a function return if it has no return statement?
Watch it
Think of it like
A vending machine. You put in arguments (coins and a button), and it returns a snack into the tray for you to take away. A machine that only flashes "Enjoy!" on its screen (print) leaves your hands empty.
Key terms
- return — Sends a value back to the caller and ends the function.
- Default parameter — A parameter with a value used when no argument is given.
- Keyword argument — An argument passed by name:
power(base=2).
Check yourself
What does return do?
def f(a, b=10): return a + b — what is f(5)?
x = print('hi') — what is x?