default argument, keyword argument, recursion
Default Argument
>>> def add(a,b):
... c = a+b
... return c
...
>>> add(3,4)
7
>>> add(3,4,5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: add() takes 2 positional arguments but 3 were given
>>>
Positional Arguments should match in numbers, if while calling we are supplying more arguments we will get error. Same case with less arguments. So, argument must match.
But there can be scenario where we want to pass optional arguments, and not all are required. Then concept of default argument can be handy.
solution,
>>> def add(a,b,c=0): # default value for c is 0, now c is not required/mandatory argument it # will take default value 0 if not supplied
... c = a+b
... return c
...
>>> add(3,4,5)
7
positional arguments follow order.
Suppose here if we don't want to pass values to the second variable, then there will be an error.
def add(a,b=0,c):
SyntaxError: non-default argument follows default argument
More about Python functions
In python, by default we are returning some value, if we don't have explicit return statement, then by default None is returned.
Example -
>>> x = f1()
Hello
>>> print(x)
None
>>> type(x)
<class 'NoneType'>
>>>
Positional arguments vs Keyword argument
keyword argument help solve problem of ordering when we are using multiple arguments in functions, we can use keyword arguments to pass values.
Example -
>>> def sum(a,b,c=0):
... print(a,b,c)
...
>>> sum(a=10,c=30,b=10)#keyword arguments
10 10 30
>>> sum(a=10,d=30,b=10) #keyword arguments
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sum() got an unexpected keyword argument 'd'
>>> sum(10,0,20)#positional arguments which follows defined #positions
10 0 20
Here, we can pass argument by using parameter name followed by = in any order. But the variable name should match in this case, otherwise we will get error.
Can we mix cases? - No if we are writing positional and keyword arguments then positional argument should proceed before keyword arguments.
>>> sum(a=10,30,b=10)
File "<stdin>", line 1
sum(a=10,30,b=10)
^
SyntaxError: positional argument follows keyword argument
Reminder
**
Syntax error - programming error (compile time error).
Runtime error - No syntax error but error during execution. .pyc file is created in this case.
The above example has syntax error, as per rule keyword argument cannot be ahead of positional argument.
sum(a=10,30,b=10) # Syntax error
sum(10,30,c=10) # correct
sum(10,a=20) # Runtime error
TypeError: sum() got multiple values for argument 'b'
No compile time error as positional argument is getting passed prior to keyword argument. But there will be an error as both values are for 'a'. This would be multiple arguments
Concept of variable argument
By using default argument, we can pass default values to a function for non-mandatory arguments.But there can be a situation where calculation is dependent on number of arguments. So in that case we have to modify existing logic to accomodate new scenario. The issue with this approach is, our earlier version become unusable.
Example - Finding average of numbers.
>>> def avg(a,b,c=0):
... return (a+b+c)/3
...
>>> avg(10,20,30) # this is working as expected
20.0
>>> avg(10,20) # there is a problem as we are dividing elements by 3 instead of 2.
10.0
>>>
Solution - use variable arguments concept.
def average(*t):
return sum(t)/len(t)
A = average(10,20,30,40,50,55)
print(A)
Here, t is a tuple which can hold multiple argument if we supply *, Now, in tuple we can apply functions to find length and required operations.
Recursion
If function calls itself, it is called recursion.
def f1():
print("Hello")
f2()
def f2():
print("Hi")
f1()
Now, if we call f1() again inside f1() then there would be a recursion.
def f1():
print("Hello")
f2()
def f2():
print("Hi")
f1()
f1()
Here, we are doing recursion by calling f1() indirectly.
f1() --> f2() --> f1()
There is a problem with this code, as f1() is getting called indefinitely inside f2() which is getting called in f1(). So, there would be recursion depth issue.
To overcome this problem, below points should be taken care.
i) Recursion should not happen indefinitely.
ii) During recursion, function should call lower complexity problem by calling self.
>>> def Num(n):
... if (n == 1):
... return 1 --> point i)
... else:
... return Num(n-1) + n --> point ii)
...
>>> Num(3)
6
>>>
Approach for recursive problem
i) Suppose we have function to solve the problem: Example - sum(n)
ii) Call existing function to solve smaller problem: sum(n-1) + n (by adding n we can solve original problem) - recursive case
iii) when to stop: if n == 1 return 1 - base case
Why recursion
There are many problems for which solutions can be achieved with recursion, solving same problems with loop doesn't yield same ease. Note: Any problem which can be solved with recursion can be solved with loops.
Comments
Post a Comment