Understanding Python's global variables and local variables
1. If the variable name inside the defined function appears for the first time and precedes the = symbol, it can be considered to be defined as a local variable. In this case, regardless of whether the variable name is used in the global variable, the local variable is used in the function. For example:
1 2 3 4 5 6 7 |
|
1 2 3 4 5 6 7 |
|
UnboundLocalError: local variable 'num' referenced before assignment
Error message: The local variable num is applied before assignment, that is, it is used without defining the variable, thus again It proves that a local variable is defined here instead of using the global num.
Summary: If the variable name inside the function appears for the first time and appears before =, it is regarded as defining a local variable.
2. If the variable name inside the function appears for the first time and appears after =, and the variable has been defined in the global domain, the global variable will be referenced here. If the variable does not exist in the global domain Definition, of course there will be a "variable is not defined" error. For example:
1 2 3 4 5 6 7 8 9 10 |
|
1 2 3 4 5 6 7 8 9 |
|
1 |
|
1 2 3 4 5 6 7 8 9 |
|
301<br>100
declare num:
1 2 3 4 5 6 7 8 9 |
|
1 |
|
301<br>300
from:
1 |
|
The above is the detailed content of Understand Python's global variables and local variables. For more information, please follow other related articles on the PHP Chinese website!