python的UnboundLocalError: local variable 'xxx' referenced before assignment
2014-06-27 16:38
453 查看
From: http://blog.sina.com.cn/s/blog_8d3652760101d01p.html
一、意思:
本地变量xxx引用前没定义。
二、错误原因
在于python没有变量的声明
, 所以它通过一个简单的规则找出变量的范围 :如果有一个函数内部的变量赋值 ,该变量被认为是本地的,所以如果有修改变量的值就会变成局部变量。
三、产生这个错误的场景
python代码:
val=9
def test(flag):
if flag:
val = 1
else:
print 'fuck'
return val
test(0)
错误提示:UnboundLocalError: local variable 'val' referenced before assignment
解决方法:用global关键字来进行说明该变量是全局变量
python代码:
val=9
def test(flag):
global val
if flag:
val = 1
else:
print 'test'
return val
test(0)
参考资料:http://www.uplook.cn/biancheng/107/1078875/
一、意思:
本地变量xxx引用前没定义。
二、错误原因
在于python没有变量的声明
, 所以它通过一个简单的规则找出变量的范围 :如果有一个函数内部的变量赋值 ,该变量被认为是本地的,所以如果有修改变量的值就会变成局部变量。
三、产生这个错误的场景
python代码:
val=9
def test(flag):
if flag:
val = 1
else:
print 'fuck'
return val
test(0)
错误提示:UnboundLocalError: local variable 'val' referenced before assignment
解决方法:用global关键字来进行说明该变量是全局变量
python代码:
val=9
def test(flag):
global val
if flag:
val = 1
else:
print 'test'
return val
test(0)
参考资料:http://www.uplook.cn/biancheng/107/1078875/
相关文章推荐
- python的UnboundLocalError: local variable 'xxx' referenced before assignment
- Python的UnboundLocalError: local variable 'xxx' referenced before assignment
- Python的UnboundLocalError: local variable 'xxx' referenced before assignment
- Python:UnboundLocalError: local variable 'num' referenced before assignment
- UnboundLocalError: local variable 'XXX' referenced before assignment
- 【Python基础】之全局变量(UnboundLocalError: local variable referenced before assignment)
- 【python】UnboundLocalError: local variable 'counter' referenced before assignment
- 【Python】UnboundLocalError: local variable 'l' referenced before assignment
- 错误:UnboundLocalError: local variable 'xxx' referenced before assignment
- 【Python】UnboundLocalError: local variable 'x' referenced before assignment
- Python - UnboundLocalError: local variable referenced before assignment
- 【Python基础】Python3: UnboundLocalError: local variable 'num' referenced before assignment
- 【Python】UnboundLocalError: local variable 'l' referenced before assignment
- 全局变量报错:UnboundLocalError: local variable 'l' referenced before assignment
- [Bug fixed]UnboundLocalError: local variable 'var_Chinesename' referenced before assignment
- Python 读写当前路径下文件错误 UnboundLocalError: local variable 'file' referenced before assignment
- python的UnboundLocalError: local variable 'xxx' referenced before assignment
- 全局变量报错:UnboundLocalError: local variable 'l' referenced before assignment
- python 错误--UnboundLocalError: local variable '**' referenced before assignment
- UnboundLocalError: local variable 'mumLeafs' referenced before assignment处理方法