How to define the function in Python?

In Python, define a function to use the def statement, write the function name, parentheses. And the parameters in the brackets, and then write the function body in the indentation block. The return value of the function is returned with the return statement.

Let’s define a my_abs function that evaluates to an absolute value.

def my_abs(x):
    if x >= 0:
        return x
    else:
        return -x

Please test and call my_abs to see if the results are correct.

Note that when a statement inside a function body is executed, once the return is executed, the function completes and the result is returned. Therefore, the function within the judge and cycle through the conditions can be achieved very complex logic.

If there is no return statement, the function will return to the results after the implementation, but the result is None.

return None can be abbreviated as return.

The usage of the import is described in detail in the subsequent module section.

Empty function

If you want to define what kind of thing do not do empty function, you can use the pass statement:

def nop():
    pass

Pass statement do not do anything, what is the use?

In fact, pass can be used as a placeholder, such as now have not figured out how to write the function of the code. You can put a pass, so that the code can run up.

Pass can also be used in other statements, such as:

if age >= 18:
    pass

The lack of pass, the code will run a grammatical error.

Parameter check

When the function is called, if the number of arguments is incorrect, the Python interpreter will automatically check it out and throw a 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

But if the parameter type is not correct, Python interpreter can not help us check. Try my_abs and built-in function abs difference:

>>> 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 incoming inappropriate parameters, the built-in function abs will check out the parameters of the error, and we define the my_abs no parameter check, will lead to an if statement error, the error message and abs is not the same. So, this function definition is not perfect.

Let’s modify the definition of my_abs, check the parameter type, allowing only integer and floating point type parameters. Data type checking can be done using the built-in function isinstance ():

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 the parameter check, the function can throw an error if the wrong parameter type is passed in.

>>> 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

Errors and exception handling will be discussed later.

Returns multiple values

Can the function return multiple values?

The answer is yes.

For example, in the game often need to move from one point to another point, given the coordinates, displacement and angle. You can calculate the new 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

The import math statement represents the import math package and allows subsequent code to reference the function of sin, cos, etc. in the math package.

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 in fact this is just a false impression, Python function returns is still 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 grammar, the return of a tuple can omit the brackets, and multiple variables can receive a tuple at the same time, according to the location assigned to the corresponding value, so the Python function returns multiple values is actually returned to a tuple, but write more convenient.

Summary

  • When defining a function, you need to determine the function name and number of parameters;
  • If necessary, you can first check the data type of the parameter;
  • Function body can be used at any time to return to return to the function results;
  • Function does not return the implementation of the statement, the automatic return None.
  • The function can return multiple values at the same time, but it is actually a tuple.