When you declare variables within a function definition, they are not related to other variables with the same name outside the function, that is, the variable name is local to the function. This is called the scope of the variable. All variables are scoped to their defined blocks, starting with the point where their names are defined.
Using 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 the function, the first time we use x
the value , Python uses the value of the formal parameter declared by the function.
Next, we assign the value 2
to x
. x
is a local variable of the function. So, when we change the value within the function, the definition in the x
main block x
is not affected.
In the last print
statement, we proved that the values in the main block are x
really not affected.
Using the global statement
If you want to assign a value to a variable that is defined outside the function, then you have to tell Python that the variable name is not local, but global . We use global
statements to complete this function. Without a global
statement, it is impossible to assign a value to a variable that is defined outside the function.
You can use the values of variables defined outside the function (assuming there are no variables with the same name within the function). However, I do not encourage you to do so, and you should try to avoid doing so, as this makes the reader of the program unclear where the variable is defined. The use global
of statements can clearly indicate that a variable is defined outside 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
(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
global
Statements are used to declare x
global-so when we assign values within a function, the change is x
reflected in the values we use in the main block x
.
You can use the same global
statement to specify multiple global variables. For example global x, y, z
.
Http://woodpecker.org.cn/abyteofpython_cn/chinese/ch07s03.html
Python local variables and global variables