It was assumed that a local variable is a variable inside the function/def/class/lambda, and that the global variable is the variable that precedes it. However, once again, a special case was found in the application of the Python ATM (unexpected)
After the dictionary changes its partial value inside the function, the dictionary is printed outside the function, and the value of the dictionary changes.
x = {"W": 1,"k": 2}defA (x): x["W"] = 123x= {"W": 999,"k": 3433} returnxdefV (): C=A (x)Print(x) v ()
and searched the Internet. Python global variables and local variable definitions
1. The name of the variable inside the defined function is assumed to be a local variable if it is first present and before =, whether or not the function name is used in the global variable
num = tendef func (): num = print# value is+ func ()print # value is ten
Furthermore
num = tendef func (): num = num + print(num) func () Print (num)
Will error: Unboundlocalerror
num = tendef func (num): num = num + print(num) func (num)print (num)
Passing in a parameter in a function does not, at this point num is the global variable in the function
2. Global Declaration of variables
D = 6def A (): Global d print(d) = d + 2131 def V (): = A () print(d) v ()
After the global is declared inside the function, the value of D is modified, and the value of the globals is changed. (This function cannot pass in parameter D, otherwise global D will error)
3. Sometimes you want to refer to a global variable inside a function, and inadvertently the following error occurs:
var = 1def Fun (): print(var) =print(fun ())------ ------------------------------------= 2def Fun (): =var + 2 return varprint(Fun ())
4. Dictionaries
X1 = {"W": 1,"k": 2}x2= {"o": 3,"P": 2}defA (x2): x1["W"] = 123X2= {"o": 999,"P": 343} returnx1,x2defV (): C=A (x2)Print(x1,x2) v ()
{' K ': 2, ' W ': 123} {' P ': 2, ' O ': 3}
X1 = {"W": 1,"k": 2}x2= {"o": 3,"P": 2}defA (X1,X2): x1["W"] = 123X2= {"o": 999,"P": 343} returnx1,x2defV (): C=A (X1,X2)Print(x1,x2) v ()
Output value: {' K ': 2, ' W ': 123} {' P ': 2, ' O ': 3}
Python local variables and global variables