Traceback (most recent call last): File "C:/Users/Sure/PyProject/day10/exercise.py", line 227, in <module> print(func()) File "C:/Users/Sure/PyProject/day10/exercise.py", line 225, in func b += 1 UnboundLocalError: local variable 'b' referenced before assignment
错误代码:
1 2 3 4 5
b = 100 deffunc(): b += 1 return b print(func())
错误原因:
在局部空间修改全局变量,但是没有声明。
解决方法:
不建议在局部空间修改全局变量。如果一定要修改,使用global声明。
1 2 3 4 5 6
b = 100 deffunc(): global b b = b + 1 return b print(func())
1.2
报错信息:
1 2 3 4 5 6
Traceback (most recent call last): File Assignment, line 249, in <module> func() File Assignment, line 247, in func print(name) UnboundLocalError: local variable 'name' referenced before assignment
错误代码:
1 2 3 4 5
name = '宝元' deffunc(): print(name) name = 'alex' func()