Args and Kwargs
Lets learn about *args
and **kwargs
keywords that show up alot as parameters in functions.
def add_func(a,b):
print(a+b)
add_func(2,3)
5
Our function can take only two input parameters a
and b
.
*args
To make a function so that it accepts, practically unlimited, number of input paramters, we use the *args
keyword. It will build the tuple out of your input parameters.
def add_func(*args):
print(sum(args))
add_func(2,3,4,5,6,7,8)
35
**kwargs
It will build a dictionary of key:value pairs based on your input.
def func(**kwargs):
print(kwargs)
func(name='muzammil',fruit='apple',balls=3)
{'name': 'muzammil', 'fruit': 'apple', 'balls': 3}
Let’s combine both *args
and **kwargs
.
def func(*args,**kwargs):
if 'fruit' in kwargs.keys():
print(f"I have {sum(args)} number of {kwargs['fruit']}")
else:
pass
func(2,3,fruit='apple')
I have 5 number of apple
Leave a comment