local and global variables

Global variables : write at the top, no spaces, can be called at any time

name='lhf'

Local variables : variables in subprograms, such as x=1 in a function, if there are global variables x=1 and local variables x=1 at the same time, then the local variables will be executed, if there are no local variables, the global variables will be executed (there is no more at home). Go outside to find, layer by layer, until you find the outermost layer)

 name='“lfe”

 def change_name():
     global name
     name = ' Beautiful than ' 
     print ( ' change_name ' ,name)

But local variables only take effect inside the function

name = " adf " 
def change_name():
     global name #If this is adding a global name (that is, a global variable, that is, name="adf") 
    name = ' handsome than ' 
    print ( ' change_name ' ,name)
 print (name )
'Beautiful one '

Error case: taking the global variable after the name local variable will cause the name value to be used to not be found, because the local variable should be used first and name = "self", but according to the top-down rule, the global name must be used , which will create a contradiction and report an error.

Solution: Therefore, global variables should be capitalized as much as possible, and local variables should be lowercase as much as possible, which is easier to distinguish.

NAME = [ " Product Manager " , " Liao Bo Shi " ]
  def qupengfei():
     name = " myself " 
     global name print ( ' I'm going to do it ' , NAME
      )
 qupengfei()

Nested functions pay attention to the order of use, example 2

NAME = ' Sea Breeze '

def huangwei():
    name = "黄伟"
    print(name)
    def liuyang():
        name = "刘洋"
        print(name)
        def nulige():
            name = ' Huzhihua ' 
            print (name)
         print (name)
        nulige ()
    liuyang()
    print(name)

5. For example, see vertical layout

name = "刚娘"

def weihou():
    name = "陈卓"
    def weiweihou():
        global name   
        name = "冷静"

    weiweihou()
    print(name)

print(name)
weihou()
print (name)
 # gangniang 
# chenzhuo 
# calm

6. New concept, nonlocal (upper level variable)

 

name = "刚娘"

def weihou():
    name = " Chen Zhuo " 
    def weiweihou():
         gnonelocal name    # nonlocal , specify the upper-level variable, if not, continue up until found 
        name = " calm "

    weiweihou()
    print(name)

print(name)
weihou()
print (name)
 # gangniang 
# calm 
# gangniang ***

 

Guess you like

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