Thirteen, python basis: Scope 2 (global reserved word) variables

Thirteen, python basis: Scope 2 (global reserved word) variables

Global variables:

Variable entire program can be called directly. Whether you are used in which function, it can be called directly.

Local variables:

Only variable in the function call. When you define a variable inside a function, it can only be called within the function.

Why should we distinguish between global and local variables it?

Global variables are usually used to temporarily hold data, a program may call multiple functions for data processing, inter-related process continues, each function will be to modify these data, if there is no global variables to temporary data, you call a function each, all incoming raw data, it can not be done step by step implementation of the process.

If we want to use global variables in a function, you must add a "global name your variables" in the above variables, declare the variables are global, not local variables.
For example, the following function, if you do not add global declared within a function, error.

a = 0
def add():
    a += 1
    print(a)

add()  

Here Insert Picture Description

Coupled with the global can use the variable a.

a = 0
def add():
    global a
    a += 1
    print(a)

add()

Here Insert Picture Description

About the scope of variables, in the back of the closure of the school, will be involved in a nonlocal reserved word, closure will involve the definition of a function within another function, this time there might use a nonlocal. About the difference between global and nonlocal, I have another article specifically noted:
explore the difference between global and nonlocal python in the purely personal understanding, there are different views Comments are welcome to explore the area

But if the foundation were not enough, now you will find difficult to understand.
Look behind the closure when that again.

Published 55 original articles · won praise 77 · views 9493

Guess you like

Origin blog.csdn.net/Jacky_kplin/article/details/104817342