In Python, you define a function to use a def statement, write out the function name, parentheses, the arguments in parentheses, and a colon, and : then, in the indent block, write the function body, and the return value of the function is returned with a return statement.
Let's take the example of customizing a function that asks for an absolute value my_abs :
def my_abs (x): if x >= 0: return x Else: return -xPrint my_abs (1)print my_abs (-1)
Please test it yourself and call to my_abs see if the result is correct.
Note that when the statement inside the function body executes, the function executes and returns the result as soon as it is executed return . Therefore, it is possible to implement very complex logic within a function through conditional judgments and loops.
If there is no return statement, the result is returned after the function is executed, except for the result None .
return Nonecan be abbreviated to return .
Null function
If you want to define an empty function that does nothing, you can use a pass statement:
def NOP (): Pass
passWhat's the use of a statement that doesn't do anything? passit can actually be used as a placeholder, like the code that's not yet ready to write the function, so you can put one pass in place so the code can run.
passIt can also be used in other statements, such as:
def my_abs (x): if x >= 0: return x Else: Pass Print my_abs (1)print my_abs (-1)
Is missing pass , the code runs with a syntax error.
Parameter check
When calling a function, if the number of arguments is incorrect, the Python interpreter automatically checks out and throws TypeError :
>>> my_abs (1, 2) Traceback (most recent ):"<stdin>" in <module>1 argument (2 given)
However, if the parameter type is incorrect, the Python interpreter will not be able to check it for us. Try my_abs the differences with built-in functions abs :
>>> my_abs ('a')'a'>>> abs (' A') Traceback (most recent): "<stdin> " in <module>for'str'
When an inappropriate parameter is passed in, the built-in function abs checks for a parameter error, and we my_abs do not define a parameter check, so the function definition is not perfect.
Let my_abs 's modify the definition, check the parameter type, and allow only integers and floating-point type parameters. Data type checking can be implemented with built-in functions isinstance :
def my_abs (x): if not isinstance (x, (Int,float)): Raise TypeError (' badoperand type') if x >= 0: return x Else: return -X
Once the parameter check has been added, the function can throw an error if it passes in the wrong parameter type:
>>> my_abs ('A') Traceback (most recent call last): " <stdin>" in <module> "<stdin>" in my_abstypeerror:bad operand type
Error and exception handling will be discussed later.
Return multiple values
Can a function return multiple values? The answer is yes.
For example, in the game often need to move from one point to another point, give the coordinates, displacements and angles, you can calculate a new new coordinates:
Import Math def Move (x, y, step, angle=0): = x + step * math.cos (angle) = Y-step * Math.sin (A Ngle) return NX, NY
So we can get the return value at the same time:
>>> x, y = Move (MATH.PI/6)print x, y151.961524227 70.0
But this is just an illusion, and the Python function returns a single value:
>>> r = Move (MATH.PI/6)print R (151.96152422706632, 70.0)
The original return value is a tuple! However, in syntax, the return of a tuple can omit parentheses, and multiple variables can receive a tuple at the same time, by the location of the corresponding value, so the Python function returns a multi-value is actually returned a tuple, but it is more convenient to write.
Summary
When defining functions, it is necessary to determine the number of function names and parameters;
If necessary, the data type of the parameter can be checked first;
The function body can return return the function result at any time;
Automatic when the function is finished and there are no return statements return None .
A function can return multiple values at the same time, but is actually a tuple.
Python-defined functions