Python中UnboundLocalError: cannot access local variable XXX where it is not associated with a value解决办法
文章目录
代码:
a = 1
def test():
a += 1
test()
运行代码报错:
UnboundLocalError: cannot access local variable 'a' where it is not associated with a value
解决方案:
1. 声明 test 函数内部变量 a 为全局变量
a = 1
def test():
global a # 将变量a声明为全局变量
a += 1
test()
在运行完test(),变量a的值成功变成了2
2. 在 test 函数内先将变量 a 初始化
a = 1
def test():
a = 0 # 声明内部变量a
a += 1 # 此时被修改的变量a与全局变量a并没有关系
test()
在运行完 test() 后,全局变量a的值并没有被修改
以上两种解决方案解决了报错问题,具体怎么改根据自己的需求来选择