/    /  Python – Functions with Keyword Arguments

Python Functions with Keyword Arguments

Python supports defining the function and calling it by using keyword arguments. While defining a function, we may or may not give default values.

Even though we provide default values for some parameters in the function, we can call the function by assigning new values by giving keyword arguments.

In Python, we have Required Keyword argument and Optional Keyword Argument. If we provide default values for a parameter in the function, then it is called Optional Keyword Argument.

If we do not provide any default value for a parameter in the function, then we must assign a value while calling it, this is called a Required Keyword Argument.

While assigning keyword arguments, we will assign a value to a parameter by assignment operator (=). Here, passed Keyword Argument must be the same with the Actual Keyword Argument which is defined in the function. Order is not necessary for functions with keyword arguments.

Let us study in more detail.

A function add has three numbers int1, int2, int3. Values of int1, int2, and int3 are given by calling the function with keyword arguments. Here, three parameters are Required Keyword arguments.

Python code:

def add(int1, int2, int3):
       result=int1+int2+int3
       return result
result=add(int1=10, int2=20, int3=30)
print(result)

Output:
60

If a function has at least one default value, then it is defined and called as shown below.

A function family has three parameters father_name, number_of_children, city. If we provide default values for number_of_children and city then, they are called as Optional keyword Arguments and father_name will be the Required Keyword Argument.

Python Code:

def family(father_name, city='Delhi',number_of_children='2'):
    print(father_name, 'lives in',city ,'with',number_of_children,'children')
 family(father_name='ram')   

Output:

ram lives in Delhi with 2 children

If we assign values of parameters using keyword arguments, we need not to follow the order of parameters or arguments.

Python Code:

family(city=’Mumbai’, father_name=’Fawad’)

Output:

Fawad lives in Mumbai with 2 children