Passing parameters of functions in Python and passing python Functions
1. Passing common parameters
>>> def add(a,b):return a+b>>> print add(1,2)3>>> print add('abc','123')abc123
2. The number of parameters is optional. parameters are passed by default.
>>> def myjoin(string,sep='_'):return sep.join(string)>>> myjoin('Test')'T_e_s_t'>>> myjoin('Test',';')'T;e;s;t'
>>> def myrange(start=0,stop,step=1):print stop,start,stepSyntaxError: non-default argument follows default argument
The default value of the sep parameter is '_'. If this parameter is not specified, the default value is used. If this parameter is specified, the given value is used.
Note that if a parameter is an optional parameter, all the parameters following it should be optional, in addition, if the order of optional parameters is reversed, the corresponding parameter values can still be correctly assigned, but the variable name and value must be clearly specified.
3. variable parameters
>>> def printf(fmt,*arg):print fmt%arg>>> printf ('%d is larger than %d',2,1)2 is larger than 1
* Arg must be the last parameter in the function. * It represents any number of parameters. * arg will put all parameters except the previous one in a tuple and pass them to the function, can be accessed through arg in the function
Arg is a tuple. You can access arg in the function by accessing tuple.
Another way to pass any number of parameters is to use a dictionary to pass multiple parameters, but each parameter must specify the name correspondence relationship, such as a = 1, B = 2, c = 3
>>> def printf(format,**keyword):for k in keyword.keys():print "keyword[%s] %s %s"%(k,format,keyword[k])>>> printf('is',one=1,tow=2,three=3)keyword[three] is 3keyword[tow] is 2keyword[one] is 1
These methods can be used together, but attention must be paid to the order. The function will first accept fixed parameters, then the optional parameters, then any parameters (tuple), and then dictionary any parameters (dict)