【Python基础】Python3: UnboundLocalError: local variable 'num' referenced before assignment
2017-03-06 20:29
597 查看
num = 0 def cal(): num += 1 print(num) cal()
Python3下,运行以上代码出错,错误为:
UnboundLocalError: local variable 'num' referenced before assignment
Python的局部变量在没有被赋值之前被引用了
不明白,然后Google了一下,说是Python的局部变量问题,Python在函数内部会把变量默认定义为局部变量。
解决办法:
在函数内部把num声明为全局变量。num = 0
def cal():
global num
num += 1
print(num)
cal()
相关文章推荐
- 【Python基础】之全局变量(UnboundLocalError: local variable referenced before assignment)
- Python:UnboundLocalError: local variable 'num' 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 'x' referenced before assignment
- python的UnboundLocalError: local variable 'xxx' 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
- 全局变量报错 UnboundLocalError: local variable 'todayPrice' referenced before assignment
- python "UnboundLocalError: local variable 'log_f' referenced before assignment" 错误
- python 错误--UnboundLocalError: local variable '**' referenced before assignment
- python的UnboundLocalError: local variable 'xxx' referenced before assignment
- python文件运行报错:UnboundLocalError: local variable 'status' referenced before assignment
- 全局变量报错:UnboundLocalError: local variable 'l' referenced before assignment
- python:UnboundLocalError: local variable 'xxx' referenced before assignment
- [Bug fixed]UnboundLocalError: local variable 'var_Chinesename' referenced before assignment
- UnboundLocalError: local variable 'mumLeafs' referenced before assignment处理方法