Python from entry to practice: basic knowledge of functions (function definition, formal participation and actual parameters)

Table of contents

1. Function introduction

Second, the definition of the function

3. Function call

 4. Formal Participation and Actual Parameters

 5. The use of formal participation and actual parameters

5.1 Positional parameters

5.2 Keyword arguments

5.3 Default parameters

5.4 Variable length parameters

5.5 Combined use

6. Namespace

6.1 Built-in namespaces

6.2 Global namespace

6.3 Local Namespaces

7. Scope


1. Function introduction

Many times, we need to apply a function repeatedly. For example, when we design a web page, we will repeatedly use the "login" function. We can write it as a function and encapsulate it, so that we can call it at any time. This can enhance the readability of the program to a certain extent and make the degree look clearer.

Second, the definition of the function

The use of functions must follow the principle of defining first and calling later . The definition of a function is equivalent to saving the code of the function body in advance, and then assigning the memory address to the function name. The function name is a reference to this code, which is similar to the definition of a variable . Calling a function without prior definition is equivalent to referencing a variable name that does not exist.

def 函数名(参数1,参数2,...):
    """文档描述"""
    函数体
    return 值

 There are a few things to note about the above definition:

1. def: keyword to define a function;

2. Function name: The function name points to the memory address of the function, which is a reference to the code of the function body. Function naming should reflect what the function does;

3. Brackets: Parameters are defined inside the brackets. The parameters are optional, and there is no need to specify the type of the parameter;

4. Colon: Add a colon after the parentheses, and then start indenting the code of the function body on the next line;

5. ""Document description""": The document describing the function function, parameter introduction and other information is not necessary, but it is recommended to add it to enhance the readability of the function;

6. Function body: composed of statements and expressions;

7. Return value: Define the return value of the function, return is optional.

#有参函数
def my_min(x,y):
    res=x if x < y else y
    return res

#无参函数
def interactive():
    user=input('user>>: ').strip()
    pwd=input('password>>: ').strip()
    return (user,pwd)

Whether we use parameterized functions or non-parameterized functions mainly depends on our needs

If the function body is pass, it means to do nothing, which is called an empty function. It is usually useful to define an empty function, because at the beginning of program design, it is often necessary to think about what functions the program needs to complete, and then list all the functions and use pass as a "placeholder" for the function body, which will make the program The architecture is immediate, clear and readable.

3. Function call

The use of functions is divided into the definition phase and the calling phase. When defining a function, only the syntax is detected, and the code of the function body is not executed. The function name is called with parentheses, and the code of the function body is executed only when the function is called.

#定义阶段
def foo():
    print('in the foo')
    bar()
 
def bar():
    print('in the bar')
 
#调用阶段
foo()

If you need to return the result of the function body code execution to the caller, you need to use return . If there is no value after return or return is omitted directly, it will return None by default. The return value of return has no type restrictions, and multiple return values ​​can be placed into a tuple .

return is a sign of the end of a function. There can be multiple returns in a function, but the function ends after only one execution , and the value defined after return is returned as the result of this call.

>>> def test(x,y,z):
...     return x,y,z #等同于return (x,y,z)
... 
>>> res=test(1,2,3)
>>> print(res)
(1, 2, 3)

 4. Formal Participation and Actual Parameters

Function parameters are divided into formal parameters and actual parameters, referred to as formal parameters and actual parameters: formal parameters are parameters declared in parentheses when defining a function. The formal parameter is essentially a variable name, which is used to receive the value from the outside.

 5. The use of formal participation and actual parameters

5.1 Positional parameters

1. When defining a function, the formal parameters are defined in order from left to right, which are called positional parameters. All formal parameters defined in this form must be passed by value

2. When calling a function, the actual parameters are defined in sequence from left to right, which are called positional parameters. All actual parameters defined in this form will correspond to the formal parameters in the order from left to right

5.2 Keyword arguments

When calling a function, the actual parameter can be in the form of key=value, which is called a keyword parameter. Any actual parameter defined in this form may not be defined in the order from left to right at all, but it can still be specified for the specified form. When assigning parameters, it should be noted that when calling a function, the actual parameters can also be mixed by position or keyword, but it must be ensured that the keyword parameter is behind the position parameter, and it is not possible to repeatedly assign a value to a formal parameter

5.3 Default parameters

When defining a function, the formal parameter has been assigned a value. This type of formal parameter is called a default parameter. When the function has multiple parameters, it is necessary to define the parameter whose value changes frequently as a positional parameter, and the parameter whose value changes less Defined as default parameters. For example, to write a function to register student information, if most of the students are male, then the formal parameter sex can be defined as the default parameter.

The parameter sex has been assigned a value when it is defined, which means that it is not necessary to assign a value to sex when calling, which reduces the complexity of function calling

Note: 1. The default parameter must be after the positional parameter 2. The value of the default parameter is only assigned once in the function definition phase

 

>>> x=1
>>> def foo(arg=x):
...     print(arg)
... 
>>> x=5 #定义阶段arg已被赋值为1,此处的修改与默认参数arg无任何关系
>>> foo()
1

The value of a default parameter should usually be set to an immutable type 

>>> def foo(n,arg=[]):
...     arg.append(n)
...     return arg
... 
>>> foo(1)
[1]
>>> foo(2)
[1, 2]
>>> foo(3)
[1, 2, 3]

5.4 Variable length parameters

Mainly the use of * and **, please refer to my previous blog for a detailed explanation: The use of * and **

5.5 Combined use

In summary, all parameters mentioned above can be used in any combination, but the order of definition must be: positional parameters, default parameters, *args, **kwargs . Variable parameters *args and keyword parameters *kwargs are usually used in combination. If the formal parameters of a function are args and **kwargs, it means that the function can receive parameters of any form and length

>>> def wrapper(*args,**kwargs):
...     pass
...

6. Namespace

The namespace is the place where the mapping/binding relationship between names and objects is stored. For x=3, Python will apply for memory space to store object 3, and then store the binding relationship between the name x and 3 in the name space, and delx means to clear the binding relationship.

6.1 Built-in namespaces

It is generated/recycled with the startup/shutdown of the python interpreter, so it is the first namespace to be loaded, used to store some built-in names, such as built-in function names

6.2 Global namespace

Generated/recycled along with the start/completion of python file execution, it is the second namespace to be loaded, and the names generated during file execution will be stored in this namespace, as follows

6.3 Local Namespaces

Temporarily generated/recycled with the call/end of the function, the formal parameters of the function and the names defined in the function will be stored in this namespace

The loading order of the namespace is: built-in namespace -> global namespace -> local namespace, and to find a name, it must be found from one of the three namespaces, and the search order is: local namespace -> bureau namespace -> Built-in namespaces.

7. Scope

According to the scope of the name, the three namespaces can be divided into two areas:

1. Global scope: the names in the global namespace and the built-in namespace belong to the global scope, and the names in this scope survive globally (unless deleted, otherwise survive the entire file execution process), globally valid (in any position can be used);

2. Local scope: Names located in the local namespace belong to the local scope. The names in this range survive temporarily (that is, they are temporarily generated when the function is called, and released after the function call ends), and they are locally valid (can only be used within the function)

Scope priority

When searching for a name in the local scope, the starting position is the local scope, so first search the local namespace, if not found, then go to the global scope to search: first search for the global namespace, if not found, then search for the built-in namespace, and finally all If not found, an exception will be thrown

x=100 #全局作用域的名字x
def foo():
    x=300 #局部作用域的名字x
    print(x) #在局部找x
foo()#结果为300
x=100
def foo():
    x=300 #在函数调用时产生局部作用域的名字x
foo()
print(x) #在全局找x,结果为100

Tip: You can call the built-in functions locals() and globals0 to view the names of the local scope and the global scope respectively, and the results are all in dictionary format . The result of locals0 viewed in the global scope is equal to globals()

When the value of the actual parameter is a variable type, the modification of the value in the function body will directly reflect the original value

num_list=[1,2,3]
def foo(nums):
    nums.append(5)
 
foo(num_list)
print(num_list)
#结果为
[1, 2, 3, 5]

 For nested multi-level functions, use the nonlocal keyword to declare the name from the scope of the outer nested function definition (non-global)

def  f1():
    x=2
    def f2():
        nonlocal x
        x=3
    f2() #调用f2(),修改f1作用域中名字x的值
    print(x) #在f1作用域查看x
 
f1()
 
#结果
3

Guess you like

Origin blog.csdn.net/weixin_43507744/article/details/126580494
Recommended