First, the definition function
In Python, to be used to define a function def
statement sequentially write the function name, parentheses, brackets and colon parameters :
, then, write the function block body is in the retracted, with the return value of the function return
return statement.
We customize the absolute value of a my_abs
function as an example:
def my_abs(x): if x >= 0: return x else: return -x
And call your own test my_abs
to see returns results are correct.
Please note that statements inside the function body at the time of execution, if implemented to return
the time, the function completes and returns the results. Thus, the internal function is determined by the conditions and the cycle can achieve very complex logic.
If there is no return
statement after the completion of function execution will return results, but the result is None
. return None
It can be abbreviated return
.
When you define a function in Python interactive environment, will pay attention to Python ...
prompt. After the function definition need to press Enter twice to return to >>>
the prompt:
>>> def my_abs(x): if x>=0: return x else: return -x >>> print(my_abs(-9)) 9 >>> my_abs(-9) 9 >>>
If you have already my_abs()
saved function is defined as abstest.py
a file, then you can start the Python interpreter in the current directory of the file, with the from abstest import my_abs
import my_abs()
function, pay attention to abstest
is the filename (without .py
extension):
Detailed usage in subsequent import module
Second, the empty function
If you want a definition of doing nothing is an empty function, you can use pass
the statement:
def nop(): pass
pass
Statement does not do anything, then what's the use? In fact, pass
it can be used as a placeholder, for example, now have not figured out how to write the code function, you can put a first pass
, so that the code can be up and running.
pass
Can also be used in other statements, such as:
if age >= 18: pass
Missing pass
, the code will be running a syntax error.
Third, check the parameters
When you call the function, if not the number of parameters, Python interpreter will automatically check it out and throw 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 not correct, Python interpreter will not be able to help us check. Try my_abs
and built-in functions abs
differences:
>>> my_abs('A') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in my_abs TypeError: 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 incoming inappropriate parameters, built-in function abs
checks the parameters of the error, and our definition my_abs
has no parameter check, will lead if
the statement error, error message and abs
not the same. So, this function definition is not perfect.
Let's change the my_abs
definition of parameter types do check, allowing only integer and floating point types of arguments. Data type checking can be built-in functions isinstance()
implemented:
def my_abs(x): if not isinstance(x, (int, float)): raise TypeError('bad operand type') if x >= 0: return x else: return -x
After adding a parameter check, if the incoming wrong parameter types, functions, you can throw an error:
>>> my_abs('A') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in my_abs TypeError: bad operand type
Detailed error and exception handling in the subsequent.
Fourth, a plurality of return value
Functions can return multiple values it? The answer is yes.
For example in the game often need to move from one point to another point coordinates are given, and the displacement angle can be calculated new coordinates:
import math def move(x, y, step, angle=0): nx = x + step * math.cos(angle) ny = y - step * math.sin(angle) return nx, ny
import math
Import statement indicates math
the package and allow subsequent code references math
bag sin
, cos
other functions.
Then, we can get a return value at the same time:
>>> x, y = move(100, 100, 60, math.pi / 6) >>> print(x, y)
But this is only an illusion, Python function returns a single value remains:
>>> r = move(100, 100, 60, math.pi / 6) >>> print(r) (151.96152422706632, 70.0)
The original return value is a tuple! However, in the grammar, it returns a tuple parentheses may be omitted, and a plurality of variables may simultaneously receive a tuple, corresponds to a value assigned by location, so that, Python's return multiple values actually returns a tuple, but more convenient to write .
V. Summary
Defining a function, the function name and the determined number of parameters;
If necessary, you can do checks on the data type of the parameter;
The functions that can be used return
at any time to return a function result;
Function completes nor return
when statements automatically return None
.
Function can return multiple values simultaneously, but in fact is a tuple.