Python Global, Local and Nonlocal variables
1. Global variables
1.1 Definition
Global variables: A variable can be accessed inside or outside funtions.
1.2 Example of Usage
在函数里( Inside functions ),能用全局变量( global variables ),但不能改变其值。
Example 1.
x = "global"
def foo():
print("x inside: ", x)
foo()
print("x outside: ", x)
Output:
x inside: global
x outside: global
Example 2.
x = "global"
def foo():
x = x * 2
print(x)
foo()
Output:
UnboundLocalError: local variable 'x' referenced before assignment
1.3 global keyword(global关键字)
倘若我们想在函数内改变全局变量的值,需要用到global关键字
x = "global"
def foo():
global x
x = x * 2
print(x)
foo()
Output:
globalglobal
2. Local variables
2.1 Definition
Local variables: We can only access local variables inside functions. Local Variables will be destroyed when the function ends.
2.2 Global variable and Local variable with the same name
x = 5
def foo():
x = 10
print("Inside x = {}".format(x))
foo()
print("Outside x = {}".format(x))
Output:
Inside x = 10
Outside x = 5
3. Unlocal variables
3.1 Definition
Unlocal variables: Nonlocal variables are used in nested functions whose local scope is not defined. This means that variable can be neither in the local nor the global scope.
3.2 Example
def outer():
x = "local"
def inner():
nonlocal x
x = "nonlocal"
print("inner: ", x)
inner()
print("outer:", x)
outer()
Output:
inner: nonlocal
outer: nonlocal