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 -x
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 .
When defining functions in the Python interactive environment, note the hints that Python will appear ... . After the function definition ends, you need to press two to return to >>> the prompt:
If you have my_abs() saved the function definition as a abstest.py file, you can start the Python interpreter in the current directory of the file, from abstest import my_abs import the my_abs() function, and note the file abstest name (without the .py extension):
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:
if age >= 18: pass
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 call last): File "<stdin>", line 1, in <module>TypeError: my_abs() takes 1 positional argument but 2 were 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‘)Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in my_absTypeError: unorderable types: str() >= int()>>> abs(‘A‘)Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: bad operand type for abs(): ‘str‘
When an inappropriate parameter is passed in, the built-in function abs checks for a parameter error, and we do not define a my_abs parameter check, which results in a if statement error and a different error message abs . Therefore, this 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(‘bad operand 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): File "<stdin>", line 1, in <module> File "<stdin>", line 3, 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 mathdef move(x, y, step, angle=0): nx = x + step * math.cos(angle) ny = y - step * math.sin(angle) return nx, ny
import mathThe statement represents the import math package and allows subsequent code to reference math the function in the package sin cos .
Then we can get the return value at the same time:
>>> x, y = move(100, 100, 60, math.pi / 6)>>> print(x, y)151.96152422706632 70.0
But this is just an illusion, and the Python function returns a single value:
>>> r = move(100, 100, 60, 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's definition function