# num1 is a global variable
num1 = 1
print num1
# num2 is a local variable
def fun():
num1 = 2
num2 = num1 + 1
print num2
fun()
# the scope of global num1 is the whole program, num 1 remains defined
print num1
# the scope of the variable num2 is fun(), num2 is now undefined
print num2
结果:
1 3 1NameError: name 'num2' is not defined
example2:
num = 4
def fun1():
global num
num = 5
def fun2():
global num
num = 6
# note that num changes after each call with no obvious explanation
print num
fun1()
print num
fun2()
print num
结果:
4 5 6
在函数外定义的是全局变量,函数内部定义的是局部变量。如果全局变量在函数中使用了并更改了其值,则会生成一个同名的局部变量。所以在函数中引用全局变量并改变其值,要加上global关键字。