function, functions, mainly for: 1 to improve the reuse of code, 2 of the program modularity.
Defining functions
In Python, you use Def to define functions, and the general functions are defined as follows:
def name (Arg1,arg2,....): statements return value
Where return is used to return the result of the function execution
A simple sample is as follows:
def Times (x, y): ... return x*y ... >>> times (5,2)10>>>
The result of the function execution can be put into a variable:
>>> result=times (5,2)>>> result10>>>
Python does not need to define the type of the parameter, the return of the function result is entirely dependent on the type of the incoming parameter, in the above example, Python automatically recognizes that the passed parameter is two digits, and makes the return value, when passing in a list parameter, the result is as follows:
>>> li=[1,2,3]>>> times (li,2) [1, 2, 3, 1, 2, 3]>>>
When the string is passed in, the result is as follows:
>>> a='Hello'>>> times (a,3)'Hellohellohello '>>>
So simply summary, the incoming function parameters will be automatically recognized by Python, that is, when the operation of the ' * ' to identify and different types of parameter variables to respond differently. However, if the ' * ' does not recognize or does not support the parameters passed in, then the function will be error when running, as follows:
>>> b='x'>>> times (A, b) Traceback (most recent call last ): " <stdin> " in <module> '<stdin>' in Timestypeerror:can' str'>>>
Therefore, in the case of uncertainty, you can experiment first, the parameters passed will not cause error.
Types of function arguments
General parameters
Keyword parameter: match by parameter name
Default parameter: Default value for parameter definition without passing in value
Variable parameter: * starts with multiple parameters based on location or keyword
Specifically, a different parameter is passed in the function definition below, which represents a different meaning:
defFun (*name)#Pass in a non-quantitative parameter that will be composed of a meta-ancestordefFunc (Name=value)#defines the default value for a parameterdefFunc (**name)#Pass in a non-quantitative parameter that will be formed into a dictionarydefFunc (Name,*args)#mixed mode, extra parameters will be formed into a meta-ancestraldefFunc (Name,**args)#mixed mode, extra parameters are formed into a dictionary to be passed indefFunc (*,name=value)#Mixed mode, the following parameter name must pass through the keyword parameter
Cond.....
Python Learning--functions