When you declare variables inside a function definition, they have no relationship to other variables with the same name outside the function, i.e. variable names are local to the function . This is called the scope of the variable . The scope of all variables is the block in which they are defined, from the point where their names are defined.
use local variables
Example 7.3 Using 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 a function, the first time we use x
a value , Python uses the value of the parameter declared by the function.
Next, we 2
assign the value to x
. x
is a local variable of the function. So, when we change the value inside the function x
, the one defined in the main block x
is not affected.
In the last print
statement, we prove that the values in the main block x
are indeed not affected.
use the global statement
If you want to assign a value to a variable defined outside a function, then you have to tell Python that the variable name is not local, but global . We use global
statements to accomplish this functionality. Without global
a statement, it is impossible to assign a value to a variable defined outside a function.
You can use the value of a variable defined outside the function (assuming there is no variable with the same name inside the function). However, I do not encourage you to do this, and you should try to avoid it, because it makes it unclear to the reader of the program where the variable is defined. A using global
statement makes it clear that variables are defined outside of the block.
Example 7.4 Using the 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
(源文件:code/func_global.py)
输出
$ python func_global.py
x is 50
Changed global x to 2
Value of x is 2
它如何工作
global
语句被用来声明x
是全局的——因此,当我们在函数内把值赋给x
的时候,这个变化也反映在我们在主块中使用x
的值的时候。
你可以使用同一个global
语句指定多个全局变量。例如global x, y, z
。
http://woodpecker.org.cn/abyteofpython_cn/chinese/ch07s03.html
作者推荐:
http://www.tubemate.video