Python study notes (2) - function


1. Define the function

    To define a function, use the def statement, write the function name, parentheses, parameters in parentheses, and colon: in turn, and then write the function body in an indented block, and the return value of the function is returned with the return statement. example:

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

Empty function:

def nop():
    pass

The pass statement does nothing and can be used as a placeholder

2. Function parameters

  A. Default parameters

  The parameter setting supports default parameters, that is, when calling a function, if no parameter with a default value is entered, the function can still be executed.

def power(x, n=2):
    s = 1
    while n > 0:
        n = n - 1
        s = s * x
    return s

As the function defined above, if you write power(3) when calling, the default is to square.

Precautions:

A mandatory parameter comes first, and the default parameter comes after

Second, how to set the default parameters.

Three default parameters must point to immutable objects!

The following example illustrates the third point

When setting the default parameters, it should be noted that if the default value is L=[], and its value is changed in the function, such as adding END at the end, then the next call will add END on this basis, there is bug. example:

def add_end(L=[]):
    L.append('END')
    return L
>>> add_end()
['END']
>>> add_end()
['END', 'END']

Because the value of the default parameter L is calculated when the Python function is defined, that is [], because the default parameter L is also a variable, it points to the object [], each time the function is called, if the content of L is changed, Then the next time it is called, the content of the default parameter will change, and it is no longer the [] when the function is defined.

Improve:

def add_end(L=None):
    if L is None:
        L = []
    L.append('END')
    return L

B. Variable parameters

If you want to change the number of parameters, the first idea is that the parameter is of type list or tuple, when calling the function, you need to pass it in the form of list or tuple.

def calc(numbers):
    sum = 0
    for n in numbers:
        sum = sum + n * n
    return sum
>>> calc([1, 2, 3])
14
>>> calc((1, 3, 5, 7))
84

Using variable parameters, the number can be directly passed in. The specific improvement is to add * before the parameter. The example is as follows:

def calc(*numbers):
    sum = 0
    for n in numbers:
        sum = sum + n * n
    return sum
>>> calc(1, 2)
5
>>> calc()
0

The call here does not need to form a list and then call. If the input parameter is a list, there is no need to input one by one. You can call it like this:

>>> nums = [1, 2, 3]
>>> calc(*nums)
14

C. Keyword Arguments

Keyword parameters allow to pass in 0 or any number of parameters with parameter names . These keyword parameters are automatically assembled into a dict inside the function.

def person(name, age, **kw):
    print('name:', name, 'age:', age, 'other:', kw)
>>> extra = {'city': 'Beijing', 'job': 'Engineer'}
>>> person('Jack', 24, **extra)
name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}
Changes to kw inside the function will not change outside the function.


named keyword arguments

If you want to limit the name of keyword parameters, you can use named keyword parameters.
Named keyword parameters require a special separator *, and the parameters after * are regarded as named keyword parameters

def person(name, age, *, city, job):
    print(name, age, city, job)
>>> person('Jack', 24, city='Beijing', job='Engineer')
Jack 24 Beijing Engineer
When called, named keyword arguments must be passed in the parameter name. Namely city, job

D. Parameter type checking:

The parameter type can be checked within the function, so that the error message can be easily viewed when an error occurs.

def my_abs(x):
    if not isinstance(x, (int, float)):
        raise TypeError('bad operand type')
    if x >= 0:
        return x
    else:
        return -x
Data type checking can be done with the built-in function isinstance()

Function introduction:

    isinstance(obj, class_or_tuple, /)

    Return whether an object is an instance of a class or of a subclass thereof.
    A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
    check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)

    or ...`` etc.

3. Call the function

  Tip: You can use help(function name) to see help information.

 Some common functions: abs(); max(); hex(); int(); type conversion


—————————————————

Many examples in this study note are cited from Liao Xuefeng's website.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326946153&siteId=291194637