函数对全局变量赋值时,要加global声明
1.不添加globa声明,可以读取全局变量,但是不能赋值
>>> a=1
>>> def f():
... a=2
... print a
...
>>> f()
2
>>> a
1
2.如果不提前进行global声明,对全局变量赋值会报错
>>> a=1
>>> def f():
... print a
... a=2
... print a
...
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
UnboundLocalError: local variable 'a' referenced before assignment
>>>
3.如果在函数内对全局变量赋值,必须添加global声明
>>> a=1
>>> def f():
... global a
... print a
... a=2
... print a
...
>>> f()
1
2
>>>