**Variable scope: **
Generally, variables defined outside the function body become global variables, and variables defined inside the function are called local variables.
All scopes of global variables are readable, local variables can only be read in this function
When a function reads variables, it first reads the local variables of the function itself, and then reads the global variables
Global variables
Read, all readable
Assignment, global
Dictionary, list can be modified
Global variables are all uppercase
E.g
name ='Tim' #Global variable
def f1():
age =18 #Local variable
print(age,name)
def f2():
age=19 #Local variable
f1()f2()18 Tim
19 Tim
Global variables can also be defined inside the function:
name ='Tim' #Global variable
def f1():
age =18 #Local variable
global name #Define global variables
name ='Eric'print(age,name)f1()print(name)
Global variables are readable by default. If you need to change the value of global variables, you need to use the global definition inside the function
Special: lists, dictionaries, can be modified, but cannot be reassigned, if you need to reassign, you need to use global to define global variables inside the function
NAME =['Tim','mike'] #Global variable
NAME1 =['Eric','Jeson'] #Global variable
NAME3 =['Tom','jane'] #Global variable
def f1():
NAME.append('Eric') #The append method of the list can change the value of external global variables
print('Function name:%s'%NAME)
NAME1 ='123' #Re-assignment cannot change the value of external global variables
print('Function NAME1: %s'%NAME1)
global NAME3 #If you need to re-assign the list, you need to use global to define global variables
NAME3 ='123'print('Function NAME3: %s'%NAME3)f1()print('Outside function name: %s'%NAME)print('Outside function name1: %s'%NAME1)print('Outside function name3: %s'%NAME3)
NAME in the function: ['Tim','mike','Eric']
NAME1 in the function: 123
NAME3 in the function: 123
NAME outside the function: ['Tim','mike','Eric']
NAME1 outside the function: ['Eric','Jeson']
NAME3 outside the function: 123
So far, this article about the scope of python variables is introduced here. For more information about the scope of python variables, please search ZaLou.Cn
Recommended Posts