Two kinds UnboundLocalError: local variable 'xxx' referenced before assignment solution to the situation

1) Operation subroutine of global variables, such as

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

test(0)


Error: UnboundLocalError: local variable 'val' referenced before assignment Solution: global keyword to be indicating that the variable is a global variable

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

test(0)

  2) local variable, but still reported a problem unboundLocal Error

such as:

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

Error: UnboundLocalError: local variable 'bbb2' referenced before assignment
reason given is that python think bbb2 not necessarily be assigned.

Solution: The first assignment for bbb2

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


 

Guess you like

Origin blog.csdn.net/asdfsadfasdfsa/article/details/90207739