1. Global variables and local variables
These two variables are the same as variables in other languages. Global variables are simply variables that can be used throughout the code. Its scope is the entire function, and Local variables have a limited scope, often within a code area.
It should be noted that if you just call the value of the global variable in the function without changing its value, there is no problem at all, but if you want to change the value of the global variable in the function without special processing, The Python language handles this situation by automatically generating a local variable with the same name as the called global variable, which means that the global variable is shielded, and operations on the variable will not affect the value of the global variable. (Although it looks like it has changed)
For example, in the following program, although the value of count is changed in the function, the value of count printed outside the function is still 5.
1 2 3 4 5 |
|
If you have to modify the value of a global variable inside the function, you can use the keyword global to modify the variable inside the function. This means that the operation is an operation on the global variable, rather than generating an Global variables are the same as local variables.
1 2 3 4 5 6 7 |
|
2. Embedded (internal) function
In short, an embedded function is a function defined inside the function
It is worth noting that the internal function can only be called outside of it Function call, but cannot be called outside. In other words, who has the right to use it within who owns it.
1 2 3 4 5 |
|
3. Closure
A closure is the parameter used by an embedded function to call its external function.
You need to pay special attention when calling this function.
1 2 3 4 |
|
4. Variable problems in closures
The following code will report an error when executed. Because the parameters of the external function are called inside the embedded function, and the parameter x is a global variable for the function Fun2(), due to the shielding effect, the function error occurs.
1 2 3 4 |
|
There are two ways to solve the above problem:
One is to use non-stack data structure to solve the problem
The second is to use the nonlocal keyword to solve the problem
1 2 3 4 5 6 7 8 9 |
|
You need to think carefully about the variables in the function. After all, there are some differences from what you learned before.
The above is the content of the seven variables and built-in functions of Python's zero-based introduction. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!