Variable scope:
In general, variables defined in the function body are called global variables, and variables defined in the function body are called local variables.
When a function is called, it usually reads its own local variable before reading the global variable.
You can access global variables within a function, but to modify global variables, you need certain conditions:
If the global variable is a mutable data type , you can modify it directly:
DIC = {0:0, 1:1, 2:2}def F (): dic[3] = 3f () print dic>>{0:0, 1:1, 2:2, 3:3}
If the global variable is an immutable data type , or you want to re-assign a value to a mutable data type :
You need to use the Global keyword
LST = [1,2,3]def f (): lst = ' hehe ' print lstf () print lst>> ' hehe ' >> [[+]
LST = [1,2,3]def f (): global lst lst = ' hehe ' print lstf () print lst>> ' hehe ' >> ' hehe '
That is, lists and dictionaries can be modified directly within the function;
To re-assign a value, you need to use the Global keyword. (Immutable data types such as String, Integer, tuple, modify = = Assignment)
Scope of the Python variable