1. If the variable name in the function appears before = for the first time, it is regarded as defining a local variable, no matter whether the variable name is used in the global domain, the function uses local variables, for example:
num = 100def func(): num = 123 print(num)func()
Output:
123
The num defined in the function is a local variable that overwrites the global variable. For example:
num = 100def func(): num += 100 print(num)func()
Output:
Unboundlocalerror: local variable 'num' referenced before assignment
The error message is that the local variable num is applied before the value assignment, that is, it is used if the variable is not defined. This proves that a local variable is defined here, rather than the global num used.
Conclusion: If the variable name in the function appears before = for the first time, it is considered to define a local variable.
Python makes educated guesses on whether variables are local or global. It assumes that any variable assigned a value in a function is local.
From: http://www.tutorialspoint.com/python/python_modules.htm
2. If the variable name in the function appears for the first time after = and has been defined in the global domain, the global variable is referenced here, if the variable is not defined in the global domain, the "variable undefined" error will certainly occur. For example:
num = 100def func(): x = num + 100 print(x)func()
Output:
200
Indicates that the num used here is the global variable num.
Or when you use this variable (for example, call a member function), global variables are also referenced. For example:
a = [1, 2]def func(): a.append(3) print(a) func()
Output:
[1, 2, 3]
Summary: as long as the * use * variable is defined in the whole local area, but not in the local area, the global variable is used.
3. When a variable is used in a function, the variable name contains both global variables and local variables with the same name. For example:
num = 100def func(): num = 200 x = num + 100 print(x)func()
Result:
300
Summary: If the variables used are defined in the whole local area and are also defined in the local area, local variables are used by default.
4. In a function, if you want to assign a value to a global variable, you must use the global life keyword. For example:
num = 100def func(): global num num = 200 print(num)func()print(num)
Output:
200
200
If the value of num in the function is 200, It is the modified global variable, and no new local variable is defined here, so subsequent operations on num are also the global variables of the operation, for example:
num = 100def func(): global num num = 200 num += 100 print(num)func()print(num)
Output:
300
300
Conclusion: To assign a value to a global variable in a function, use the global keyword.
By: