Local and global variables
1. Global variables: Variables that take effect globally
name = 'lhf' #The top is written without indentation, and takes effect in the entire py file
def fox ():
name = "sb"
print ("shuaige", name) #This name is inside the fox () function, which is a local variable
fox () #The name output here is "sb"
print ( name) #The name output here is the global variable "lhf"
If you want to change the global variable in the function, you can try the following method
name = 'lhf' #No indentation at the top is effective in the entire py
def fox ():
global name
name = "sb"
print ("shuaige", name) #The name inside is inside the fox () function Is a local variable
fox () #The name output here is "sb"
print (name) #The output result is "sb", because global name is to change the global variable
Piggy Page's supplement: there is no global in the function, priority is to read local variables, if not, the global variables are read,
if there is global, the global variables are modified
name = "sb"
def a ():
global name #Changes to global variables
name = "2b"
print ("i fcuk", name)
def b ():
name = "haha"
print ("i want to fuck ", name) #Although the global variable has changed, but when calling the function b, it uses its own local variable
a ()
b ()
print (name) # At this time, the global variable has changed and becomes 2b
! ! ! Global variables are all uppercase and local variables are all lowercase ! ! !
Exercise:
def weihou (): name = "chenzhuo" def weiweihou (): global name #Add global at a deeper level, and do not affect the internal preference of the internal variable name = "lengjing" weiweihou () print (name) print (name) weihou () print (name) #Output result: gangniang chenzhuo lengjing
Expanding exercises
def weihou (): name = "chenzhuo" def weiweihou (): nonlocal name #! ! ! Nonlocal here refers to the modification of the upper-level variable without modifying the global variable name = "lengjing" weiweihou () print (name) print (name) weihou () print (name) #Output result: gangniang # lengjing # gangniang