← Python lessons

Parameters & Return

Parameters are the names a function uses for values supplied by its caller. return supplies a result back to that caller. Read Defining Functions first.

Parameters and arguments

def greet(name):
    print(f"Hello, {name}!")

greet("Ada")
greet("Bo")

name is the parameter. "Ada" and "Bo" are arguments: the actual values supplied by each call. A fresh call uses its own value.

Return a result

def subtract(first, second):
    return first - second

answer = subtract(10, 3)
print(answer)
print(subtract(3, 10))

The results are 7 and -7. Positional arguments match parameters in order. The caller can store, print or use the returned value in another calculation.

return is not print

print() displays a value. return ends the current function call and hands a value back to its caller.

def show_double(number):
    print(number * 2)

result = show_double(3)
print("result is:", result)

This displays 6, then result is: None. A function with no returned value produces None, even if it printed something.

def double(number):
    return number * 2

result = double(3)
print(result + 1)

This prints 7. Put return after a loop when the whole loop must finish; returning inside it ends the function on that iteration.

Keep function data local

Use parameters for the values a function needs. Names assigned inside a function normally belong to that call; return results you need outside it. Do not rely on an unrelated variable elsewhere in the program.

Your turn

Complete triple with one return statement.

def triple(number):
    # Return three times number.
    pass

answer = triple(4)
print(answer)

Expected output

12

See also: Decomposition, Printing Output.


Practise this in the free Python course, where every exercise checks your code instantly.