Python local variables and global variables global, pythonglobal
When you declare variables in the function definition, they have no relationship with other variables with the same name outside the function, that is, the variable name isLocal. This is called VariableScope. The scope of all variables is the block they are defined, starting from the point where their names are defined.
Use local variables
Example 7.3 use local variables
#!/usr/bin/Python
# Filename: func_local.py
def func(x):
print 'x is', x
x = 2
print 'Changed local x to', x
x = 50
func(x)
print 'x is still', x
(Source file: code/func_local.py)
Output
$ python func_local.py
x is 50
Changed local x to 2
x is still 50
How it works
In the function, we usexOfValuePython uses the parameter value declared by the function.
Next, we set the value2Assignedx.xIs the local variable of the function. So when we change in the functionxIn the main block.xNot affected.
In the lastprintStatement, we prove thatxIs not affected.
Use global statements
If you want to assign a value to a variable defined outside the function, you have to tell Python that the variable name is not local,Global. We useglobalStatement to complete this function. NoglobalIt is impossible to assign values to variables defined outside the function.
You can use the value defined outside the function (assuming there is no variable with the same name in the function ). However, I do not encourage you to do this, and you should avoid it as much as possible, because this makes the reader of the program unclear where the variable is defined. UseglobalThe statement clearly indicates that the variable is defined outside the block.
Example 7.4 use a global statement
#!/usr/bin/python
# Filename: func_global.py
def func():
global x
print 'x is', x
x = 2
print 'Changed local x to', x
x = 50
func()
print 'Value of x is', x
(Source file: code/func_global.py)
Output
$ python func_global.py
x is 50
Changed global x to 2
Value of x is 2
How it works
globalStatement is used to declarexIs Global -- therefore, when we assign the value to the FunctionxThis change is also reflected in the usex.
You can use the sameglobalThe statement specifies multiple global variables. For exampleglobal x, y, z.
Http://woodpecker.org.cn/abyteofpython_cn/chinese/ch07s03.html