Page 286 - Computer Science Class 11 With Functions
P. 286
Skipping a default parameter and specifying a subsequent parameter will generate an error as shown below:
>>> interest(55000,,1)
SyntaxError: invalid syntax
1. Default parameters: Default parameters take the default values provided in the function definition when the
default parameters are not specified in a function call.
2. Default parameters: When the values of default parameters are specified in a function call, the default values
provided in the function definition are ignored.
3. All non-default parameters (if any) should precede the default parameters.
11.2.2 Keyword Arguments
By default, the arguments in a function call are specified in the same sequence as in the formal parameter list. So, to
compute the simple interest considering 55000 as the value of the principal, 4 as the rate of interest, and 2 as the
time in years, we may invoke the interest() function as follows:
>>> interest(55000, 4, 2)
4400.0
However, note that the interest rate 4 is already a default parameter. But we had to specify it as we could not have
specified the time (2), skipping the rate parameter in the middle. Fortunately, Python allows us to specify the
input arguments to a function in an arbitrary order by explicitly associating the names of the formal parameters with
their values using the following syntax:
formal_paramter = argument value
For example, we can modify the above call to the function interest, skipping the parameter rate as follows:
>>> interest(55000, time = 2)
4400.0
Keyword arguments are often used when the default parameter list is quite long, and we wish to assign a user-specified
value for only a few of them. For example, consider the following function fun:
>>> def fun(n1 = 10, n2= 20, n3 = 30, n4 = 40, n5 = 50, n6 = 60):
return n1 + n2 + n3 + n4 + n5 + n6
>>> fun(n2 = 15, n4 = 35)
200
11.2.3 Function Argument
A function argument may be an object of any Python type. For example, functions can also be passed as arguments
as shown below in Program 11.2:
Program 11.2 Function Calls as Function Parameter
01 def applyFn(f, x):
02 '''
03 objective: To demonstrate the use of a function as an argument
04 Input Parameters:
05 f: function being passed as argument
06 x: argument for invoking f
07 Return Value: f(x)
08 '''
09 return f(x)
Now, let us see some example of the use of above function:
>>> applyFn(abs, -4)
4
>>> import math
>>> applyFn(math.sqrt, 16)
284 Touchpad Computer Science-XI

