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:
view code image
...: """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):
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):
Out[3]: 30
The following call to rectangle_area has arguments for both length and width, so IPython ignores the default parameter values:
Out[4]: 50
KEYWORD ARGUMENTS
When calling functions, you can use keyword arguments to pass arguments in any order. To demonstrate keyword arguments, we redefine the rectangle_area function—this time without default parameter values:
view code image
...: """Return a rectangle's area."""
...: return length * width
...:
Each keyword argument in a call has the form parametername=value. The following call shows that the order of keyword arguments does not matter—they do not need to match the corresponding parameters’ positions in the function definition:
view code image
Out[3]: 50
In each function call, you must place keyword arguments after a function’s positional arguments—that is, any arguments for which you do not specify the parameter name.
Such arguments are assigned to the function’s parameters lefttoright, based on the argument’s positions in the argument list. Keyword arguments are also helpful for improving the readability of function calls, especially for functions with many arguments.