We can also use default parameter values in our user-defined functions. Looking at our last example, we could assign a default value for the parameter b, say b = 5. This value would be used unless an argument is provided to overwrite it when the function is called. Example
def
addition(a, b = 5):
return a + b
print(addition(2))
This
would give 7.
def
addition(a, b = 5):
return a + b
print(addition(2, 8))
This
would give 10.
We could have as many parameters as required.
However, the default parameters always come after the positional parameters
have been specified so we do not get error messages when we run our code.
def
addition(a, b, c = 3, d = 4):
return a + b + c + d
print(addition(2, 8))
This
would give 17.
If we do
not know how many parameters and hence, how many arguments the function would
take, we could use the (*args). For example
def
addition(*num):
for a in num:
return sum(num)
print(addition(1, 2, 3, 4, 5, 6, 7, 8))
This would
be 36.
Lastly,
let us discuss what docstrings are in relation to functions. They are optional
documentation a bit similar to comments but they provide documentation for what
your user-defined function does so others can read up on it especially for
complex programs. They are enclosed within triple quotation marks. Example
def
addition(*num):
'''This function performs addition
of all the arguments provided to it'''
for a in num:
return sum(num)
print(addition(1, 2, 3, 4, 5, 6, 7, 8))
When we
now run
print(addition.__doc__)
The
docstring we included would be printed.
We could
try it for inbuilt functions like print and input too.
print(print.__doc__)
print(input.__doc__)
We can
now update our calculator program.
No comments:
Post a Comment