Function --- Defined Functions

First, the definition function

In Python, to be used to define a function defstatement 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 returnreturn statement.

We customize the absolute value of a my_absfunction as an example:

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

And call your own test my_absto see returns results are correct.

Please note that statements inside the function body at the time of execution, if implemented to returnthe 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 returnstatement after the completion of function execution will return results, but the result is None. return NoneIt 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.pya file, then you can start the Python interpreter in the current directory of the file, with the from abstest import my_absimport my_abs()function, pay attention to abstestis the filename (without .pyextension):

 

 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 passthe statement:

def nop():
    pass

passStatement does not do anything, then what's the use? In fact, passit 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.

passCan 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_absand built-in functions absdifferences:

>>> 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 abschecks the parameters of the error, and our definition my_abshas no parameter check, will lead ifthe statement error, error message and absnot the same. So, this function definition is not perfect.

Let's change the my_absdefinition 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 mathImport statement indicates maththe package and allow subsequent code references mathbag sin, cosother 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 returnat any time to return a function result;

Function completes nor returnwhen statements automatically return None.

Function can return multiple values ​​simultaneously, but in fact is a tuple.

Guess you like

Origin www.cnblogs.com/Tomorrow-will-be-better/p/11142253.html