Global and local variables

#Global variable; the first is the global variable, that is, the variable without indentation; 
#local variable can be called anywhere ; the variable defined in the subroutine


name = " test "             #global variable

def func(): #This                 function is a local scope 
    global name             #Define a global variable; the above test will be modified 
    name = " many to many "         #local variable 
    print (name)
func()
print(name)


#If there is no global in the function; read local variables first; if there are no local variables, all variables are read; but global variables cannot be reassigned; but for variable types; internal operations can be performed on it 

s = [ " a " , " b " ]
 def func1():
    s.append( ' c ' )        # for mutable types; can do internal operations on it 
    print (s)             # ['a', 'b', 'c'] 
func1()
 print (s)                 # ['a' , 'b', 'c']


def test1():
    name = "test1"
    print(name)         #test1
    def test2():
        name = "test2"
        print(name)     #test2
        def test3():
            name = "test3"
            print(name) #test3
        print(name)     #test2
        test3()
    test2 ()
test1()


# nonlocal is to change the value of the previous layer 
def js():
    val = " aaa "      #Modified to bbb 
    def jp():
        nonlocal val #Modify the upper val to the value of the following bbb 
        val = " bbb " 
        print (val)    # bbb 
    jp()
     print (val)        # bbb 
js()

def js():
    val = "aaa"
    def jp():
        val = "bbb"
        print(val)
        return jp
    return jp
js()()

 

Guess you like

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