Beginner 12 min

Functions and return values

Give a repeatable operation a name, pass arguments to it, and use its result.

Name an operation

def creates a function. The parameters in parentheses give names to values passed by each call. Inside the function, use return to send a value back to the caller. A function that reaches the end without return yields None.

How it works

First separate the name of the recipe from the values it receives. Calling a function supplies real argument values. The return statement sends an answer back to the caller. Try replacing the arguments while leaving the function unchanged to see that the recipe is reused.

Use the returned result

Calling a function and printing inside it are separate operations. Returning a value lets a caller print it, use it in arithmetic, or pass it into another function. Keep input and output simple so the same function can be tested in several situations.

Code example

def trip_cost(riders, fare):
    return riders * fare

subtotal = trip_cost(3, 5)
print(subtotal + 2)

Check your understanding

Predict the full cost for each rider count, with a fare of 5 per person and an extra 2 per trip.

See the example and explanation
Example 1
Given 1
Answer 7
Example 2
Given 4
Answer 22

The function returns riders * 5. The final operation adds 2. For four riders the full cost is 22.

Open practice problem
Next lessonErrors and input validation