To pass a variable-length key-value pair as an argument to a function, Python provides a feature called **kwargs.
kwargs stands for Keyword arguments. It proves to be an efficient solution when one wants to deal with named arguments in their function.
Syntax:
def functionName(**anything):
statement(s)
Note: adding ‘**‘ to any term makes it a kwargs parameter. It accepts keywords as arguments.
Example #1:
Python3
def printKwargs( * * kwargs):
print (kwargs)
if __name__ = = "__main__" :
printKwargs(Argument_1 = 'gfg' , Argument_2 = 'GFG' )
|
Output:
{'Argument_1': 'gfg', 'Argument_2': 'GFG'}
Example #2:
Python3
def printValues( * * kwargs):
for key, value in kwargs.items():
print ( "The value of {} is {}" . format (key, value))
if __name__ = = '__main__' :
printValues(abbreviation = "GFG" , full_name = "geeksforgeeks" )
|
Output:
The value of abbreviation is GFG
The value of full_name is geeksforgeeks
Example #3:
Python3
def concatenate( * * arguments):
final_str = ""
for elements in arguments.values():
final_str + = elements
return final_str
if __name__ = = '__main__' :
print (concatenate(a = "g" , b = "F" , c = "g" ))
|
Output:
gFg
Example #4:
Python3
def multiply( * * kwargs):
answer = 1
for elements in kwargs.values():
answer * = elements
return answer
if __name__ = = '__main__' :
print (multiply(a = 1 , b = 2 , c = 3 , d = 4 , e = 5 ))
|
Output:
120
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!