Python:UnboundLocalError: local variable 'num' referenced before assignment
2018-02-05 14:17
489 查看
源代码
num = 1 def test(): num += 1 return num print(test())
错误详情
可能原因
python中出现了没有声明的变量 , py是通过如下简单的规则找出变量的范围 :如果函数内部有对变量的赋值 ,则该变量被认为是本地的,此时可以正常修改。但是若变量不定义在函数内部,且没有进行变量范围的声明(去调用外部变量),程序在函数内部找不到相应变量,所以会出现未定义变量的错误提示消息。解决方案
将变量声明为全局变量,在调用的时候使用global关键词,则可以正常访问,正确代码如下:num = 1 def test(): global num num = num + 1 return num print(test()) # 输出结果:2
参考文章:
https://www.cnblogs.com/sola-tester/p/4323008.html
相关文章推荐
- 【Python基础】Python3: UnboundLocalError: local variable 'num' referenced before assignment
- 【Python】UnboundLocalError: local variable 'x' referenced before assignment
- Python的UnboundLocalError: local variable 'xxx' referenced before assignment
- Python - UnboundLocalError: local variable referenced before assignment
- 【Python】UnboundLocalError: local variable 'l' referenced before assignment
- 【Python】UnboundLocalError: local variable 'l' referenced before assignment
- python的UnboundLocalError: local variable 'xxx' referenced before assignment
- python的UnboundLocalError: local variable 'xxx' referenced before assignment
- 【python】UnboundLocalError: local variable 'counter' referenced before assignment
- 【Python基础】之全局变量(UnboundLocalError: local variable referenced before assignment)
- Python的UnboundLocalError: local variable 'xxx' referenced before assignment
- 全局变量报错:UnboundLocalError: local variable 'l' referenced before assignment
- Python 读写当前路径下文件错误 UnboundLocalError: local variable 'file' referenced before assignment
- 全局变量报错 UnboundLocalError: local variable 'todayPrice' referenced before assignment
- 错误:UnboundLocalError: local variable 'xxx' referenced before assignment
- UnboundLocalError: local variable 'XXX' referenced before assignment
- [Bug fixed]UnboundLocalError: local variable 'var_Chinesename' referenced before assignment
- python的UnboundLocalError: local variable 'xxx' referenced before assignment
- Python问题:UnboundLocalError: local variable 'xxx' referenced before assignment
- UnboundLocalError: local variable ' ' referenced before assignment