Functions
def starts a function. The names in the parentheses are parameters. The caller passes values for them.
return ends the function and gives a value back. Code after return does not run.
A function is a named calculation. You write the steps once. You call the name whenever you need that calculation again, with whatever values the call supplies. The tutorial section on functions is the reference for def, parameters, and return.
Why a function is worth naming
A one-line calculation can sit in the middle of a program. That works until you need the same calculation in two places, or you need to check it on its own. A function gives the calculation a name, a place for its inputs, and a single result.
double does not print. It returns. The two print calls are outside the function, so you can see what came back. double(4) returns 8. double(0) returns 0. The function does not remember the previous call. Each call starts fresh with the argument it was given.
Parameters and arguments
A parameter is the name in the definition. An argument is the value in the call. In def double(number), number is the parameter. In double(4), 4 is the argument. For the duration of that call, number points at 4.
- The definition names the function and its parameters.
- The body uses those parameters. It should not depend on names from outside unless you mean it to.
- The call supplies one argument for each parameter, in order.
returnhands one value back. The call expression becomes that value.
* multiplies. number * 2 is twice number. It does not change number itself. If you wrote number * 2 and forgot return, the function would hand back nothing useful, and the check would fail even though the arithmetic was right.
Match each word with what it does.
- def
- parameter
- return
Worked example
The exercise asks for twice a number. Walk through one call before you edit the box below.
- The caller evaluates
double(4). - Python binds
numberto4and runs the body. number * 2is8.returnends the function and makes the call equal to8.
The same body works for both calls because it uses the parameter, not a fixed number. A function that always returns 8 would pass one check and fail the next.
Put the lines in an order that defines double and prints 8.
print(number)
def double(number):
print(double(4))
return number * 2
A function computes twice a number and the check reads the result of the call. What should the function do with that result?
Try the example before you change the exercise.
Write a function named double that takes a number and returns twice that number.
OutputThe starter returns 0 so the page runs before you write the real body. Replace that return with an expression that uses number. Do not change the function name. The check calls double, not a name you invent.