4.9 Default Parameter Values

When defining a function, you can specify that a parameter has a default parameter value. When calling the function, if you omit the argument for a parameter with a default parameter value, the default value for that parameter is automatically passed. Let’s define a function rectangle_area with default parameter values:


In [1]: def rectangle_area(length=2, width=3):
   ...:     """Return a rectangle's area."""
   ...:     return length * width
   ...:

You specify a default parameter value by following a parameter’s name with an = and a value—in this case, the default parameter values are 2 and 3 for length and width, respectively. Any parameters with default parameter values must appear in the parameter list to the right of parameters that do not have defaults.

The following call to rectangle_area has no arguments, so IPython uses both default parameter values as if you had called rectangle_area(2, 3):


In [2]: rectangle_area()
Out[2]: 6

The following call to rectangle_area has only one argument. Arguments are assigned to parameters from left to right, so 10 is used as the length. The interpreter passes the default parameter value 3 for the width as if you had called rectangle_area(10, 3):


In [3]: rectangle_area(10)
Out[3]: 30

The following call to rectangle_area has arguments for both length and width, so IPython ignores the default parameter values:


In [4]: rectangle_area(10, 5)
Out[4]: 50

Self Check

  1. (True/False) When an argument with a default parameter value is omitted in a function call, the interpreter automatically passes the default parameter value in the call.
    Answer: True.

  2. (True/False) Parameters with default parameter values must be the leftmost arguments in a function’s parameter list.
    Answer: False. Parameters with default parameter values must appear to the right of parameters that do not have defaults.