Definition of a function
In some programming languages, function declarations and function definitions are distinguished (in these programming languages, function declarations and function definitions can appear in different files, such as C), but in Python, function declarations and function definitions are considered as one. In Python, the basic form of a function definition is as follows:
def function (params): block return expression/value
Attention:
(1) Use the DEF keyword in python to define the function without specifying the type of the return value.
(2) The function parameter params can be 0, one or more, the same, the function parameter also does not specify the parameter type, because in Python the variable is weak type, Python automatically maintains its type according to the value.
(3) The return statement is optional, it can appear anywhere in the function body, indicating that the function call executes to this end, if there is no return statement, it will automatically return none, if there is a return statement, but return does not follow the expression or value is returned to none.
>>>defPrinthello ():Print 'Hello' #no return statement>>>defTest ():Print 'This is printed' return #return to the end of the statement, indicating that the function call executes to this end Print ' This isn't'>>> x =Test () this isPrinted>>> >>>defAdd (A, B):#the params parameter can be 0, one, or multiple returnA +b>>>PrintAdd ()3>>>
Second, the use of functions
After defining a function, you can use the function, but in Python it is important to note that forward references are not allowed in Python, that is, the function is not allowed to be called until the function is defined. Let's see the following example:
1 Print Add2def Add (A, b):3 return
Results after running the program:
From the report's fault, it is known that a function named "Add" is not defined, so at any time a function is called, you must ensure that it is defined before the call .
Python Foundation 10 (function one)