python notes VII--function return value, scope and namespace, recursion

1. Return value: The return value is the result returned after the function is executed.

1. You can use return to specify the return value of a function. You can use the return value of the function, or you can receive the return value of the function through a variable.

2. What value is followed by return, the function will return what value.

Return can be followed by any object, and the return value can even be a function.


def fn():
    # return 'Hello'
    # return [1,2,3]
    # return {'k':'v'}
    def fn2() :

    return fn2 # The return value can also be a function

r = fn() # The result of the execution of this function is its return value
r() # Here r() is a function that can be called directly

3. If only one return is written or no return is written, it is equivalent to return None

def fn2() :
    a = 10
r = fn2()

Returns None.

4. In the function, the code after the return will not be executed, and the return will automatically end once the function is executed.

def fn3():

r = fn3()

The return is hello.

5. The difference between return and break and continue:

① return is used to end the function

② break is used to exit the current loop

③ continue is used to skip the current loop

def fn4() :
    for i in range(5):
        if i == 3 :
            # break is used to exit the current loop
            # continue is used to skip the current loop
            return # return is used to end a function
    print('The loop is done!')


Returns 0, 1, 2.

6. The difference between fn5 and fn5()

print(fn5) # fn5 is the function object, printing fn5 is actually printing the function object <function fn5 at 0x05771BB8>
print(fn5()) # fn5() is calling the function, printing fn5() is actually printing the return value of the fn5() function 10

2. The help() function: It is a built-in function in Python. Through the help() function, you can query the usage of functions in python

Syntax: help( function object)

help(print) # Get the usage instructions of the print() function

Third, the document string (doc str)

> When defining a function, you can write a docstring inside the function, and the docstring is the description of the function.

> When we have written the docstring, we can view the description of the function through the help() function.

> The documentation string is very simple. In fact, writing a string ''' directly in the first line of the function is the documentation string.

def fn(a:int,b:bool,c:str='hello') -> int:
    Here is an example of a docstring

    What the function does:......
    Parameters of the function:
        a,role, type, default value......
        b,role, type, default value......
        c,role, type, default value......
    return 10


4. Scope and Namespace

1. scope: refers to the area where the variable takes effect

example 1:

def fn():
    a = 10 # a is defined inside the function, so its scope is inside the function and cannot be accessed outside the function
    print('Inside the function:','a =',a)
    print('Inside the function:','b =',b)

print('Outside the function:','a =',a)
print('Outside the function:','b =',b)

Here a is defined inside the function, so its scope is inside the function and cannot be accessed outside the function.

(1) There are two scopes in Python:

① Global scope: The global scope is created when the program is executed and destroyed when the program execution ends.
- All areas outside of functions are of global scope.
- Variables defined in the global scope belong to global variables, and global variables can be accessed anywhere in the program.

② Function scope: The function scope is created when the function is called and destroyed when the call ends
- A new function scope is created each time the function is called.
- Variables defined in the function scope are local variables, which can only be accessed inside the function.

(2) Lookup of variables

When we use a variable, we will first look for the variable in the current scope,

① Use if available,

② If not, continue to search in the previous scope, if there is, use it,

③ If there is still no, continue to search in the previous scope, and so on,

④ Until the global scope is found, and still not found, an exception will be thrown NameError: name 'a' is not defined

(3) When assigning a value to a variable in a function, the default is to assign a value to a local variable. If you want to modify a global variable inside a function, you need to use the global keyword to declare the variable.

def fn3():
    # a = 10 
    global a # The use a declared inside the function is a global variable, and when you modify a at this time, you are modifying the global a
    a = 10 # Modify global variables
    print('Inside the function:','a =',a)

print('Outside the function:','a =',a)

2. Namespace: refers to the location where variables are stored. Each variable needs to be stored in the specified namespace.

scope = locals() # current namespace
# Add a key-value to the scope
scope['c'] = 1000 # Adding a key-value to the dictionary is equivalent to creating a variable in the global (generally not recommended)

(1) Each scope will have a corresponding namespace.

(2) The global namespace is used to save global variables. Function namespaces are used to store variables in functions

(3) The namespace is actually a dictionary, a dictionary specially used to store variables

(4) locals() is used to obtain the namespace of the current scope.

① If locals() is called in the global scope, the global namespace is obtained,

② If locals() is called in the function scope, the function namespace is obtained and a dictionary is returned

(5) The globals() function can be used to obtain the global namespace at any location.

def fn4():
    a = 10
    # scope = locals() # Calling locals() inside a function will get the namespace of the function
    # scope['b'] = 20 # It is possible to manipulate the namespace of functions through scope, but this is not recommended

    global_scope = globals()
    # print(global_scope['a'])
    global_scope['a'] = 30


5. Recursion: A recursive function is to call itself in a function

Recursion is a way to solve problems, it is very similar to loops. Its overall idea is to decompose a big problem into small problems, until the problem cannot be decomposed, and then solve the problem.

1. Two elements of a recursive function:

(1) Baseline conditions

- the smallest problem into which the problem can be decomposed, when the baseline condition is satisfied, the recursion is not executed anymore

(2) Recursive condition

- conditions for continuing to decompose the problem

2. Recursion is similar to loop, and can basically replace each other.

(1) Loops are easier to write and slightly harder to read
(2) Recursive writing is difficult, but easy to read

3. Infinite recursion: If this function is called, the memory of the program will overflow, and the effect is similar to an infinite loop

# def fn():
#     fn()
# fn()

Tags: Python programming language

Posted by bengan on Sat, 03 Sep 2022 10:02:33 +0530