First, what is a global variable? local variables?
Answer: A variable that takes effect globally is called a global variable, and a variable defined in a subprogram is called a local variable
When a global variable has the same name as a local variable, in the subprogram where the local variable is defined, the local variable takes effect, and the global variable takes effect elsewhere.
#-*-coding:utf-8-*-
name = "hello" #global variable
def change_name():
x= 1 #local variable
name = "hello" print ( "changename",name) change_name() #output is the local variable print name #The output is the global variable
Second, the keyword global global variable is redeclared, and the output is the variable after redeclaration
#-*-coding:utf-8-*- name = "hello" #global variable def change_name(): x=1#local variable global name name = "hello" print ("changename",name) change_name() print name #After adding global, the global variable is changed, and the output is hello
three,
#If the content of the function has no global keyword # - has declared local variables NAME = ["n","l"] # def qupengfei(): # NAME = "myself" # print('want', NAME) # qupengfei() - no declaration of local variables def qupengfei(): NAME.append("d") print('want', NAME) qupengfei()
## If the content of the function has the global keyword # - has declared local variables NAME = ["n","l"] def qupengfei(): global NAME NAME = "myself" print('want', NAME) qupengfei()
Exercise: Please output the print content: Huang Wei
Liu Yang Liu
Yang
Hu Zhi Hua
Huang Wei
def huangwei(): name = "Huang Wei" print(name) def liuyang(): name = "Liu Yang" print(name) def nulige(): name = 'Hu Index Flower' print(name) print(name) nulige () liuyang() print(name) huangwei()
Exercise 2
name = "gang" def weihou(): name = "chen" def weiweiho(): global name name ="leng" weiweiho() print name print name weihou() print name
The output is: gang
chen
leng