Python study notes 2 - functions

This article is a study note, learning resource: Python tutorial on Liao Xuefeng's official website https://www.liaoxuefeng.com/
1. Calling the function:

>>> abs(100)
100
>>> abs(-20)
20
>>> abs(12.34)
12.34
>>> max(1, 2)
2
>>> max(2, 3, 1, -5)
3

data type conversion function

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

Hit the point! ! ! !
The function name is actually a reference to a function object. You can assign the function name to a variable, which is equivalent to giving the function an "alias".
Second, define a function
1. In Python, to define a function, use the def statement. Write the function name, parentheses, parameters in parentheses, and colons in that order. Then, write the function body in an indented block, and the return value of the function is returned with the return statement.
Hit the point! ! !
When the statement inside the function body is executed, once the return is executed, the function is executed and the result is returned. If there is no return statement, the function will return the result after execution, but the result is None. return None can be shortened to return.
2. Empty function
If you want to define an empty function that does nothing, you can use the pass statement.
In fact, so that the code can run.

if age >= 88:
    pass

3. Returning multiple values
​​In fact, this is just an illusion. The Python function returns a single value.
The original return value is a tuple! However, grammatically, returning a tuple can omit the parentheses, and multiple variables can receive a tuple at the same time, and assign the corresponding value according to the position, so the Python function returning multiple values ​​is actually returning a tuple, which is more convenient to write.
3. The parameters of the function are
appended:
a star (*): indicates that the received parameters are processed as a tuple

Two stars (**): Indicates that the received parameters are handled as a dictionary

1. Positional parameters

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

2. Default parameters
Note!
One is that the required parameters come first, and the default parameters follow, otherwise the Python interpreter will report an error (think about why the default parameters cannot be placed in front of the required parameters);
the second is how to set the default parameters. When the function has multiple parameters, put the parameters with large changes in the front, and put the parameters with small changes in the back. Parameters with small changes can be used as default parameters.
What are the benefits of using default parameters?
The biggest advantage is that it can reduce the difficulty of calling functions.

def enroll(name, gender, age=6, city='Beijing'):
    print('name:', name)
    print('gender:', gender)
    print('age:', age)
    print('city:', city)

3. Variable parameters
Variable parameters means that the number of incoming parameters is variable, which can be 1, 2 to any number, or 0.

def calc(numbers):
    sum = 0
    for n in numbers:
        sum = sum + n * n
    return sum
def calc(*numbers):
    sum = 0
    for n in numbers:
        sum = sum + n * n
    return sum

Defining a variable parameter is compared to defining a list or tuple parameter, only adding a * sign in front of the parameter. Inside the function, the parameter numbers receives a tuple, so the function code is completely unchanged.
However, when calling this function, you can pass in any number of parameters, including zero
parameters a dict

def person(name, age, **kw):
    print('name:', name, 'age:', age, 'other:', kw)

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

def person(name, age, *, city, job):
    print(name, age, city, job)

Call method:

>>> person('Jack', 24, city='Beijing', job='Engineer')
Jack 24 Beijing Engineer

If there is already a variadic parameter in the function definition, the following named keyword parameters no longer need a special delimiter *

def person(name, age, *args, city, job):
    print(name, age, args, city, job)

Named keyword arguments must be passed in the parameter name, unlike positional arguments. If no parameter name is passed in, the call will report an error
Note ! ! ! !
When using named keyword arguments, pay special attention, if there are no variadic arguments, you must add a "*" as a special delimiter. If missing, the Python interpreter will not recognize positional parameters and named keyword
parameters
All parameters can be used in combination. Note , however, that the order of parameter definitions must be: required parameters, default parameters, variadic parameters, named keyword parameters, and keyword parameters.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325621405&siteId=291194637