两种UnboundLocalError: local variable 'xxx' referenced before assignment情况的解决方法

1)在子程序中对全局变量的操作,比如

val=9
def test(flag):  
    if flag:  
        val = 1  
    else:  
        print 'Error'  
    return val 

test(0)


错误提示:UnboundLocalError: local variable 'val' referenced before assignment解决方法:用global关键字来进行说明该变量是全局变量

val=9
def test(flag):
    global val
    if flag: 
        val = 1 
    else: 
        print 'test' 
    return val

test(0)

  2)局部变量,但仍然报出unboundLocal Error问题

比如:

def test(flag):
   if (a):
      bbb = aaa
   elif(b):
      bbb2 = aaa2
   print(bbb2)

错误提示:UnboundLocalError: local variable 'bbb2' referenced before assignment
报错的原因是python认为bbb2不一定能被赋值。

解决方案:先对bbb2赋值

def test(flag):
   bbb2=0
   if (a):
      bbb = aaa
   elif(b):
      bbb2 = aaa2
   print(bbb2)


 

posted @ 2019-05-14 15:28  車輪の唄  阅读(132)  评论(0编辑  收藏  举报  来源