If you want to make some of the arguments to your
function optional, you must supply a default value. In
the argument list, this looks like “”.
name=value
Here's an example of a function with one argument that
has a default value. If you call it with no arguments,
the name mood has the string value 'bleah' inside the function. If you call it
with an argument, the name mood has the
value you supply.
>>> def report(mood='bleah'):
... print "My mood today is", mood
...
>>> report()
My mood today is bleah
>>> report('hyper')
My mood today is hyper
>>>
If your function has multiple arguments, and the caller supplies multiple parameters, here is how they are matched up:
The function call must supply at least as many parameters as the function has positional arguments.
If the caller supplies more positional parameters than the function has positional arguments, parameters are matched with keyword arguments according to their position.
Here are some examples showing how this works.
>>> def f(a, b="green", c=3.5): ... print a, b, c ... >>> f() Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: f() takes at least 1 argument (0 given) >>> f(47) 47 green 3.5 >>> f(47, 48) 47 48 3.5 >>> f(47, 48, 49) 47 48 49 >>> f(47, 48, 49, 50) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: f() takes at most 3 arguments (4 given) >>>
Here is another feature: the caller of a function can
supply what are called keyword
parameters of the form “”. If the function
has an argument with a matching keyword, that argument
will be set to name=value.
value
If a function's caller supplies both positional and keyword parameters, all positional parameters must precede all keyword parameters.
Keyword parameters may occur in any order.
Here are some examples of calling a function with keyword parameters.
>>> def g(p0, p1, k0="K-0", k1="K-1"): ... print p0, p1, k0, k1 ... >>> g(33,44) 33 44 K-0 K-1 >>> g(33,44,"K-9","beep") 33 44 K-9 beep >>> g(55,66,k1="whirr") 55 66 K-0 whirr >>> g(7,8,k0="click",k1="clank") 7 8 click clank >>>