Designing a function of python which can accept variable number of arguments
In this post, we will know how to make a function in python that can accept
any number of arguments.
To make a function with variable arguments the syntax is *arg. When a function
is written with a parameter having * before it then that function can take any number of arguments in the form of a tuple.
The parameter of a function having * before it will get the arguments in the form of a tuple of all the
arguments.
Below is the example which illustrates it:
EXAMPLE-1
1 2 3 4 5 6 7 8 9 10 11 12 |
#Created a sum function with an star before its parameter def sum(*arg): sum=0 print(type(arg)) for i in arg: sum+=i return sum a=sum(10,20,30,40) print("a=",a) b=sum(1,2,3,4,5,6,7,8,9) print("b=",b) |
output:
<class 'tuple'>
a=100
<class 'tuple'>
b=45
To access parameters with their name we will make parameters with a double star before it. This will create a dictionary of arguments.
EXAMPLE-2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | def compute(**arg): print(arg) print(type(arg)) if 'base' in arg and 'power' in arg: base=arg['base'] power=arg['power'] return base**power if 'divisor' in arg and 'dividend' in arg: divisor=arg['divisor'] dividend=arg['dividend'] return dividend/divisor a=compute(base=10,power=2) print(a) b=compute(divisor=5,dividend=20) print(b) |
Output:
{'base': 10, 'power': 2}
<class 'dict'>
100
{'divisor': 5, 'dividend': 20}
<class 'dict'>
4.0
In the compute function above we have used **arg, this type of parameter will accept the arguments with their variable name and will convert it into a dictionary.
Comments
Post a Comment