In practice, Python functions may have dozens of parameters. Think of them as "tuning knobs" on how a function calculates. If a function has a dozen parameters, it is cumbersome to remember their ordering in the header, which makes it hard for a programmer to use the function. Keyword arguments allow the order to be mixed up, but if a function has 12 parameters, it would still be necessary to have 12 arguments in each call to the function.
Keyword Parameters resolve this predicament by specifying a default value for some (or all) parameters. Here is a trivial example of a function to add up five things.
1 2 | def sumfive(a,b=0,c=0,d=0,e=0):
return a+b+c+d+e
|
All parameters except the first have zero as
the default value. Because the first parameter
does not have a default value, every call to
sumfive must say what is the value for parameter
a
(whereas the others can be missing).
A few examples of calling sumfive are shown below.
def sumfive(a,b=0,c=0,d=0,e=0): |
return a+b+c+d+e |
print sumfive(3*5*7-2) |
print sumfive(1,2,3,4) |
print sumfive(2,4,6,8,10) |
print sumfive(12,d=37) |
print sumfive(c=14,a=3) |