Detailed Python's function

                                               Detailed Python's function

I. Overview of functions

     Briefly, the function is a black box, which receives an input (parameter), and then perform particular tasks to perform specific functions, to generate the final output (return value). Wherein an input (parameter) and output (return value) are optional, i.e., it may or may not have a function that perform particular tasks piece of code to accomplish a specific function. It may be defined in the program code into a certain function, and the specified input (parameter) and a function name received, so that it can be called multiple times elsewhere in the program executed by the function name and the section of each call and executes the code after, will perform a specific task according to an input (parameter) to accomplish specific functions received to generate a corresponding output (return value) defines the Python language has a number of built-in functions. We can call these built-in function by function name directly in the program. For example: When we call the built-in function ID (), an input (parameter) is an arbitrary object is to obtain a specific function completion input (parameter) the unique identifier, the output (return value) that uniquely identifies an input (parameter).


Second, why the need to function

1. If you need to reuse the code to complete a specific function in the program many times, we do not need this particular function associated code written many times in many places, can be defined as a function of the relevant code of this particular function, then call this function in more than one place, every invocation of the function corresponding to the relevant code execution again.

2. hide implementation details of the function is a black box, the implementation details hidden. Many times we do not focus on the implementation details of the function, just focus it receives input (parameter) and the generated output (return value) on it.

3. Improve the maintainability of the complete definition of certain specific features of the code, if you need to modify this code, only need to be modified in place after a function, improve the maintainability of the program. Otherwise, you need to find a number of different places this code, every place must make the same modifications, protracted and painstaking and error-prone.

4. To improve readability, easy to debug each function corresponds to a specific function completion code section, to improve the readability of the program, but also facilitates program debugging.


Third, define and call functions

1, function declarations

Function syntax

def function name ([formal parameter 1, parameter 2 form, in the form of parameters n]):

    Function body

Which, def keyword is defined in Python.


Notes function name

a) Each function has a function name for the function was called.

b) the function name belongs to the identifier, therefore, must follow the naming rules for identifiers, to comply with the recommended naming identifiers.


Description of the parameters of the form

a)  in the form of parameters referred to as parameter

b) for receiving an input parameter in the function call, the actual parameter received is passed (the argument)

c) parameter enclosed in brackets indicate optional time parameter, i.e., may or may not define the definition.

d) the nature of the parameter is a variable, its scope (scope function) is limited to the body of the function


Notes function body

a) a body is a function of subject code that perform particular tasks to perform specific functions

b) a corresponding function body code block must be indented.

c) If the function requires the output (return value), the function in vivo can be returned through the statement return xxx, while the end of the execution of the function thereof.

If the function does not require output (return value), you can directly execute the function body end function in vivo by the statement return, or let the function body is successfully completed, in fact, function in both cases there is a return value, its The return value is None.

d) the body will be executed function when calling the function, therefore, the function does not change the definition of the program execution flow.


2, function calls

The function is called, each argument are used to initialize the corresponding parameter. After all the formal parameters are initialized, the function body corresponding code block is executed. Execution flow of the program will jump to the body of the function defined functions, perform the function body corresponding block of code, executing the function body and then jump back to where the calling function, proceed to the next statement.


def test(arg1,arg2):
    if arg1 and arg2:
        return arg1 and arg2
    elif arg1 or arg2:
        return arg1 or arg2
    else:
        return False
        
print(test('hi',1)) # 1
print(test(1,[])) # 1
print(test('',[])) # False


Fourth, the location of the function call arguments

The function is called, all the parameters can be passed in accordance with the position of each parameter type argument position corresponding to each argument with the corresponding position parameter initialization, such argument called location argument.

def test1(arg1,arg2,arg3):
    print('a = ', arg1, 'b = ', arg2, 'c =', arg3)
# Different argument position, initializes the value of parameter is different, the value returned will vary
test1(1,2,3) # a =  1 b =  2 c = 3
test1(3,2,1) # a =  3 b =  2 c = 1


Five key arguments of the function call

When calling a function, the argument of the form can be transmitted: parameter name = argument values ​​to a specified value of the initialization argument specifies the name of this argument parameter called Keyword argument.

def test2(a,b,c):
    print('a = ', a, 'b = ', b, 'c = ', c)
When # call the function, you can specify the argument value of the initialization parameter specifies the name
test2(a = 1, b = 2, c = 3) # a =  1 b =  2 c =  3
test2(a = 3, b = 1, c = 2) # a =  3 b =  1 c =  2


Sixth, call the function argument passed

For immutable transmission type and argument types of variable arguments, argument passed value type variable affected by operation of the body functions. Immutable type argument is not affected.

def test3(arg1,arg2):
    arg1 * 10
    arg2.append(4)
    print(arg1,arg2)
i = 10
L = [1,2,3]
test3(i,L) # 10 [1, 2, 3, 4]

print ( 'the value of i', i, 'value L', L) 10 L value # value of i [1, 2, 3, 4]


Seven, multiple definitions of the function's return value

如果需要在调用函数后有多个返回值,可以在定义函数时在函数体内使用 return语句返回由多个返回值组成的元组。

def test4(arg1):
    even = []
    odd = []
    for i in arg1:
        if i % 2:
            even.append(i)
        else:
           odd.append(i)
    # return 定义返回两个列表的值
    return even,odd
L = list(range(1,11))

print(test4(L)) # ([1, 3, 5, 7, 9], [2, 4, 6, 8, 10])


八、函数定定义之带默认值的形参

定义函数时,可以给形参设置默认值,这样,调用函数时如果不传递对应的实参,就会使用设置的默认值初始化形参。给形参设置默认值的语法格式为: 形参=默认值 给形参设置默认值之后,可以简化函数的调用,只有与默认值不符的形参才需要传递额外的实参。

def test5(a,b = 5):
    print('a = ', a, 'b = ', b)
    
test5(10) # a =  10 b =  5 未传入b的实参,使用默认值b = 5


九、函数定义之使用*定义关键字形参

定义函数时,可以在所有形参的某个位置添加一个*,这样,*后面的所有形参都被定义为只能接收关键字实参的关键字形参。

def test6(a,b,*,c,d):
    print('a = ', a, 'b = ', b, 'c = ', c, 'd = ', d)
# 调用函数时,必须传入c = xx d = xx的关键字参数
test6(1,2,c = 3,d = 4) # a =  1 b =  2 c =  3 d =  4
#test6(1,2,3,4)  test6() takes 2 positional arguments but 4 were given


十、函数定义之使用*定义个数可变的位置形参

定义函数时,可能无法事先确定传递的位置实参的个数,在这种情況下,可以在形参前添加一个*,将形参定义为个数可变的位置形参,从而可以接收0个或任意多个位置实参。这些位置实参会将个数可变的位置形参初始化为一个元组。

def test7(arg1,*arg2):
    print('arg1 = ', arg1, '*arg2 = ', arg2)
    
# 传入实参时可以传入多个参数,arg1接收第一个参数,*arg2接收剩余的参数
test7(1,2,3,4) # arg1 =  1 *arg2 =  (2, 3, 4)


十一、函数调用之使用*将序列中的每个元素转换为位置实参

调用函数时,可以在序列前面添加一个*,从而将序列中的每个元素都转换为一个单独的位置实参。

def test8(a,b,c):
    print('a = ', a, 'b = ', b, 'c = ', c)
    
L = [1,2,3]
# 正常调用,需要依次传递L的索引作为实参,然后初始化形参
test8(L[0],L[1],L[2]) # a =  1 b =  2 c =  3
# 调用时使用*,将序列中的每一个元素转换成单独的位置实参
test8(*L) # a =  1 b =  2 c =  3


十二、函数定义之使用**定义个数可变的关键字形参

定义函数时,可能无法事先确定传递的关键字实参的个数,在这种情况下,可以在形参前添加两个*将形参定义为个数可变的关键字形参,从而可以接收0个或任意多个关键字实参。这些关键字实参会将个数可变的关键字形参初始化为一个字典。

def test9(**kwargs):
    print(kwargs)
    
#传入多个关键字实参,初始华**kwargs,以字典的形式返回值
test9(a = 1, b = 2, c = 3) # {'a': 1, 'b': 2, 'c': 3}

# 因为位置形参必须要在关键字形参之前,所以个数可变的位置参数必须在个数可变的关键字参数之前
def test10(*args,**kwargs):
    print(args,kwargs)

test10(1,2,3,a = 11, b = 12) # (1, 2, 3) {'a': 11, 'b': 12}


十三、函数调用值使用**将字典的每个键值对都转换为关键字参数

调用函数时,可以在字典前添加两个**,从而将字典中的每个键值对都转換为一个单独的关键字实参。

def test11(a,b,c):
    print('a = ',a, 'b = ', b, 'c = ', c)
    
d = {'a':1,'b':2,'c':3}
test11(**d) # a =  1 b =  2 c =  3

Guess you like

Origin blog.51cto.com/13760226/2466496