解决 Unboundlocalerror: local variable 'xxx' referenced before assignment
这段代码在函数内部没有定义 a 变量,会去函数外部寻找。
a = 1
def func():
print(a)
func()
运行:
C:\Users\L\Desktop>py 1.py
1
我试图在函数里修改外部变量的值。
a = 1
def func():
a = a + 1
print(a)
func()
运行:
C:\Users\L\Desktop>py 1.py
Traceback (most recent call last):
File "c:\Users\L\Desktop\123.py", line 7, in <module>
func()
File "c:\Users\L\Desktop\123.py", line 4, in func
a = a + 1
UnboundLocalError: local variable 'a' referenced before assignment
主要报错
UnboundLocalError: local variable 'a' referenced before assignment
翻译后意思是:
UnboundLocalError:赋值前引用的局部变量“a”
在函数前面加上一个 global a
。
a = 1
def func():
global a
a = a + 1
print(a)
func()
运行:
C:\Users\L\Desktop>py 1.py
2
完美解决。