Tuesday, 26 November 2019

**kwargs(Keyword arguments)


   **kwargs(Keyword arguments):

Example 1:
def f1(*a):
    print("a=",a)
#*args=("Hyd","vij","Kadapa")#creating tuple and storing into args var
f1(5) #valid output: a=5 since we can send non keyword argument
f1(a=5)#error we can not send keyword argument to the function

Example 2:
def f1(**args):
    print("a=",args)
#f1(5)# error due to non keyword argument
f1(a=5)#valid as it is keyword output: a={1,5} in the form of dictionary

Python passes variable length non keyword argument to the function using *args but we cannot use this to pass keyword argument. For this problem Python has got a solution called **kwargs, it allows us to pass the variable length of keyword arguments to the function.
We use the double asterisk ** before the argument (parameter). The arguments are passed as a dictionary and these arguments make a dictionary inside function with name same as the parameter excluding double asterisk **.

Example 3: Using **kwargs to pass the variable keyword arguments to the function

def student(**data):
    print("\nData type of argument:",type(data))
    for key, value in data.items():
        print("{} is {}".format(key,value))
student(name="Sita", Age=22, Phone=1234567890)
#student(name="Ram", Email="ram@gmail.com", course="MCA", Age=25, Phone=9876543210)
"""output:
Data type of argument: <class 'dict'>
name is Sita
Age is 22
Phone is 1234567890
>>>
"""
*args and *kwargs are special keyword which allows function to take variable length argument.
*args passes variable number of non-keyworded arguments list and on which operation of the list can be performed.
**kwargs passes variable number of keyword arguments dictionary to function on which operation of a dictionary can be performed.
*args and **kwargs make the function flexible.

def display(a,** kwarg):#**kwarg can take 0 or more values to display given values
    print("fp",a)
    for i,j in kwarg.items():
        #items() gives pairs of item
        print('key={},value={}'.format(i,j))
"""
Insteag of kwarg,we can give any identifier
output:
1. >>> display(2,rno=5)
fp 2
key=rno,value=5
>>> 
2.>>> display(3,rno=4,name='ramesh')
fp 3
key=rno,value=4
key=name,value=ramesh
>>>

"""
In Python Dictionary, items() is used to return the list with all dictionary keys and values.

Syntax: dictionary.items()
Parameters: This method takes no parameters.


str.format() is one of the string formatting methods in Python3, which allows multiple substitutions and value formatting. This method lets us concatenate elements within a string through positional formatting.



You may like the following posts:
Formal and actual parameters


1 comment:

Files with Exception handling

#Ask the user to take two input integer values var a,b try:     a=int(input("enter any integer value:"))     b=int(input(...