写了个小例子练手,报错:
Traceback (most recent call last):
File “game.py”, line 74, in < module >
update_total(True, 10) File “game.py”, line 70, in update_total
total = total + num
UnboundLocalError: local variable ‘total’ referenced before assignment
代码如下:
total = 200
def update_total(is_add, num):
if is_add:
total = total + num
else:
total = total - num
update_total(True, 10)
print('total = ' + str(total))
为啥呢?
单步调试进去,发现在函数内部是可以访问函数外部定义的total变量的
E:\code\python>python -m pdb game.py
e:\code\python\testcode\game.py(3)()
(Pdb) b 74
Breakpoint 1 at e:\code\python\testcode\game.py:74
(Pdb) c
e:\code\python\testcode\game.py(74)()
-> update_total(True, 10)
(Pdb) s
–Call–
e:\code\python\testcode\game.py(68)update_total()
-> def update_total(is_add, num):
(Pdb) s
e:\code\python\testcode\game.py(69)update_total()
-> if is_add:
(Pdb) n
e:\code\python\testcode\game.py(70)update_total()
-> total = total + num
(Pdb) total
200
(Pdb) total + num
210
(Pdb) n
UnboundLocalError: “local variable ‘total’ referenced before assignment”
e:\code\python\testcode\game.py(70)update_total()
-> total = total + num
(Pdb)
函数内部可以访问total变量,total = total + num却会出错,说明问题出现在了赋值语句上
当然通过报错信息也直接说明了问题出现在赋值语句上
查询python文档,找到global的使用:
The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global.
global语句是针对当前整个代码块的声明。这意味着列在其后的所有标识符将被解析为全局有效的。不用global给全局变量赋值是不可能实现的,尽管自由变量可以引用全局变量而不用声明为全局的。
所以修改为:
在total变量赋值前,声明total是全局变量即可
total = 200
def update_total(is_add, num):
global total
if is_add:
total = total + num
else:
total = total - num
update_total(True, 10)
print('total = ' + str(total))