The usual way to define simple functions is
by putting positional parameters in the
header of the definition. As an example,
let subadd
be a function that
subtracts the second parameter from the
first, then adds the third parameter and
returns the value.
1 2 3 | def subadd(first,second,third):
x = first-second
return x+third
|
The usual way to use the function is
just by listing the arguments in order,
subadd(3,2,1)
will return 2.
Keyword arguments relax the ordering.
Putting in the names of the parameters
enables the ordering to be mixed up, but the
names match up and give the correct result.
Step through the following to see it working.
def subadd(e,r,y): |
x = e-r |
return x+y |
T = subadd(2**5,3*10,9-(2*3)+17) |
print subadd(y=15/3,e=2,r=T) |
print 100 + subadd(r=7,e=2*5,y=T) |
Observe that calculating a value for T involves first binding the results of expressions to positional parameters. This can be seen in the stepper trace, going forward through the function evaluation of subadd.
The last two calls to subadd use keyword arguments, which can also put in expressions for the arguments, or even named values defined earlier in the program.
The question is, why would anyone ever want to use keyword arguments? At this point, the only reason would appear to be that the order of the parameters is unclear, but the names of the parameters are easier to remember.