Python – Functions wih Special Parameters
Python Functions with Special Parameters
Python have the special forms of parameters in functions. These special forms of parameters are Args and Kwargs. Args is a special parameter through which any number of positive arguments packed into a tuple. Through Kwargs any number of Keyword Arguments packed into a dictionary.
Args is represented by *args
Kwargs is represented by **Kwargs
*args is a special syntax in function definitions which is used to pass a non-keyworded variable number of arguments to a function. To take variable number of arguments, * is used in the syntax. With *args, any number of arguments can be appended on to the current parameters.
def fruits(*args): for arg in args: print (arg) fruits(‘Mango’, ‘Apple’, ‘Guava’, ‘Banana’)
We can also make iterative statements by using *args. In the given example, we are defining two statements. In which first is non iterative and second is iterative statements. The values are assigned by calling the function.
def numbers(arg1, *args): print (“First number: “, arg1) for arg in args: print(“Next number: “, arg) numbers(‘one’, ‘two’, ‘three’, ‘four’, ‘five’)
First number: one
Next number: two
Next number: three
Next number: four
Next number: five
Kwargs is a special syntax in function definitions which is used to pass keyworded, variable-length argument list. In syntax we use double star before Kwargs. It is represented as **Kwargs.
Double star allows us to pass values through keyword arguments. Kwargs is a dictionary which maps each keyword to the value which we pass alongside it. When we call the iterative function, there will not be any order.
def winner(**kwargs): for key, value in kwargs.items(): print ("%s : %s " %(key, value)) winner(first ='ross', second ='john', third='mike')
first : ross
second : john
third : mike