Possible Duplicate:
local var referenced before assignment
Python 3: UnboundLocalError: local variable referenced before assignment
test1 = 0
def testFunc():
test1 += 1
testFunc()
我收到以下错误:
UnboundLocalError: local variable 'test1' referenced before assignment.
Error说'test1'
是局部变量,但我认为这个变量是全局变量
那么它是全局的还是局部的,如何在不将全局test1
作为参数传递给testFunc
的情况下解决这个错误呢?
必须指定test1是全局的:
最佳解决方案:不要使用
global
s为了在函数内部修改
test1
,需要将test1
定义为全局变量,例如:但是,如果只需要读取全局变量,则可以不使用关键字
global
打印它,如下所示:但是,当需要修改全局变量时,必须使用关键字
global
。相关问题 更多 >
编程相关推荐