Agrs and kwargs stands for arguments, key and word arguments. Actually the idea behind args ans kwargs is that it happens many times when we don’t know how many parameters a function will take then this args and kwargs are very useful.

*Agrs can take any no. of arguments and **kwargs can take any no. of key and value pair i.e, like dictionary. Let us see through examples.

How to use args and kwargs

Function using *args

In [76]:

## Creating a function which can take multiple(any no. of ) arguments
## Here in this example it is not much necessary to give unknown number of parameters
## But in some cases we are not knowing then this *args is very useful

def office_hours(*args):
    return ('Hi!'+ str(args[0]) +' Your office hours will be ' + str((int(args[2].split(':')[0]) - int(args[1].split(':')[0])))+ 
              ' hours.')

In [77]:

## calling the above function



'Hi!Rajesh Your office hours will be 8 hours.'

In [79]:

## You can pass any no. of arguments though last parameter we are not using in our function



'Hi!Rajesh Your office hours will be 8 hours.'

Function using **kwargs

In [69]:

## function which is taking multiple or any no. of agruments
## **kwargs takes input in the form of dictionary only.

def multiple_args(**kwargs):
    ## printing key and value pair.
    for key, value in kwargs.items():
        print('Key is {0} and value is {1}'.format(key,value))

In [70]:

## creating a dictionary to be passed in the function
emp_office_hours = dict(name = 'Rajesh', hours = 8)

## calling function with dictionary as input

Key is name and value is Rajesh
Key is hours and value is 8

Calling a function with multiple arguments

It is opposite to above one in that function definition can takes any no. of arguments. Here we are having fixed no. of arguments in function but using multiple inputs(tuple, list) how can we execute a function. If you remember we have discussed zip then it is somewhat similar to that one but not fully.

In [71]:

def office_hours(start_time,finish_time):
    return ('Hi! Your office hours will be ' + str((int(finish_time.split(':')[0]) - int(start_time.split(':')[0])))+ 
              ' hours.')

In [74]:

args = ('10:00','18:00')


'Hi! Your office hours will be 8 hours.'

Hope, you are able to understand the concept of args and kwargs. Though these examples are not much upto the usage of args and kwargs, but will try to cover the usage of these concepts in upcoming blogs like in decorators function.

Hope you are enjoying these blogs. Stay tuned! Keep learning with us.

Leave a Comment

Your email address will not be published. Required fields are marked *