Global and local variables in python

  The essential difference between global variables and local variables is the scope. Global variables can be accessed anywhere in the entire program. For local variables, try to declare variables inside the function. When the function ends, the local variables will be released by memory.

example:

1 name= ' zs ' 
2  def change():
 3       name= ' ls ' 
4       change()
 5  print (name)    #The output is: 'zs' The name in the function is a local variable, and it disappears after the function runs

If you want to modify a global variable, declare it with the keyword global inside the function.

1 name= ' zs ' 
2  def change():
 3      global name
 4      name= ' ls ' 
5  change()
 6  print (name)      #The output is ls   

In fact, local variables are hierarchical. If there is nesting of functions, if the inner function wants to call the outer variable, it cannot be declared with global, because the outer variable is not called a global variable. At this time, if you want to modify the outer variables, you have to use a new keyword: nonlocal  

 

#Forcibly using the global variable will report an error, the following code can be run by yourself

def fun():
    a = 3

    def fun2():
        global a
        a*= 2
        print(a)

    return fun2()
fun()       

 

 If you use nonlocal it can be solved perfectly:

 1 def fun():
 2     a = 3
 3 
 4     def fun2():
 5         nonlocal a
 6         a*= 2
 7         print(a)
 8 
 9     return fun2()
10 fun()           #输出 6

 

Guess you like

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