Knowledge points about Python global variables and local variables

#Knowledge point one:

#The variable defined outside the function is called the global variable
num = 100

def AAA():
  '''
  If you modify the global variable directly in the function, an exception will occur.
  If you really need to modify it, you can declare it in the function (add global in front)
  '''
  global num
  print(num)
  num+=2
  print(num)

def BBB():
  print(num)

AAA() #Output 100 and 102
#After calling the function AAA(), the value of the global variable num really changes
BBB() #Output 102

 


#Knowledge point 2:
'''
If the global variable is a variable type, such as a list or a dictionary, it can be modified directly in the function;
while for immutable types, such as int, it cannot be modified directly in the function
'''
nums = [11,22,33]
info = {"name":"xiaowang","age":24}

def test():
  print("-"*20)
  # nums.append(44) #List can be modified in function
  # print(nums)
  info['name'] = 'xiaoli'
  print(info)

def test2() :
  print("="*20)
  # print(nums)
  print(info)

test()
test2( ) #The
above two printing results are the same

 


#Knowledge point 3:
#In order to prevent the same name as the local variable, add a g before the global variable
# g_a = 200
a = 200

def test3():
  print("-"*20)
  #a+=1 #In this case, the value of a is directly modified, but since a outside the function is a global variable that cannot be modified within the function, an error

  a = 100 will be reported
  '''
  Note 1: This may be to redefine a new variable a, or it may be to modify the value of a, but since the global
  variable a cannot be modified, a redefine a is here;
  Note 2: If a local variable The name is the same as the global variable, then the local variable
  '''
is used   print(a)

def test4():
  print("="*20)
  print(a)
  #print(b) # name 'b' is not defined
  # The order of use of variables is: local variables -> global variables, if there are neither, the program will report an error

test3() #print 100
test4() #print 200

Guess you like

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