Define, then use, define the stage only to judge the syntax, do not execute the code. Above define the stage if 1>2 print ... There is a syntax error, so the error, below, called a non-existent variable, not a syntax error
First, call the function
Python has built in a lot of useful functions that we can call directly.
To invoke a function, you need to know the name and parameters of the function, such as a function that asks for an absolute value abs , and only one argument. Documents can be viewed directly from the official Python website:
Http://docs.python.org/3/library/functions.html#abs
You can also help(abs) view the abs function's help information on the interactive command line.
Call abs function:
>>> abs(100)100>>> abs(-20)20>>> abs(12.34)12.34
When calling a function, if the number of arguments passed in is incorrect, the error will be reported TypeError , and Python will tell you explicitly that abs() there are only 1 parameters, but two are given:
>>> abs(1, 2)Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: abs() takes exactly one argument (2 given)
If the number of arguments passed in is correct, but the parameter type cannot be accepted by the function, TypeError the error is reported, and an error message str is given: is the wrong parameter type:
>>> abs(‘a‘)Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: bad operand type for abs(): ‘str‘
Instead max , the function max() can receive any number of arguments and return the largest one:
>>> max(1, 2)2>>> max(2, 3, 1, -5)3
Data type conversions
Python's built-in common functions also include data type conversion functions, such as int() functions that convert other data types to integers:
>>> int(‘123‘)123>>> int(12.34)12>>> float(‘12.34‘)12.34>>> str(1.23)‘1.23‘>>> str(100)‘100‘>>> bool(1)True>>> bool(‘‘)False
The function name is actually a reference to a function object, and it is possible to assign a function name to a variable, which is equivalent to giving the function an "alias":
>>> a = abs # 变量a指向abs函数>>> a(-1) # 所以也可以通过a调用abs函数1
Second, define the functionIn Python, you define a function to use the
defstatement, which in turn writes out the function name, parentheses, arguments in parentheses, and colons
:, and then, in the indent block, write the function body, and the return value of the function is
returnStatement is returned.
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 (call function, define function)