Home > Software design >  local variable 'sbang' referenced before assignment
local variable 'sbang' referenced before assignment

Time:11-07

I am trying to return an array that has 1 added to the value represented by the array given the array of any length but I get this error once I execute my code:

UnboundLocalError: local variable 'sbang' referenced before assignment

My code is :

def up_array(arr):
    
    for i in arr:
        if i < 0:
            return None
        if i > 9:
            return None
        else:
            sbang = ''.join(map(str, arr))
    a = "0" str(1 (int(sbang)))
    b = [int(x) for x in str(a)]
    
    if sbang[0] == "0" and len(sbang) > 2:
        return b
    else:
        a = 1 (int(sbang))
    c = [int(x) for x in str(a)]
    return c

Any help would highly be appreciated.

I am expecting digits in the array to be added by 1 while saving leading zeros and if there are digits lower than zero and higher than 9 to return None.

What I got was that some of the digits were calculated while for others I got error:

local variable 'sbang' referenced before assignment

CodePudding user response:

In your code if arr is empty then the for loop will not be executed and sbang will never be initialized. You can fix it by doing:

def up_array(arr):

    for i in arr:
        if i < 0:
            return None
        if i > 9:
            return None
    sbang = "".join(map(str, arr))
    a = "0"   str(1   (int(sbang)))
    b = [int(x) for x in str(a)]

    if sbang[0] == "0" and len(sbang) > 2:
        return b
    else:
        a = 1   (int(sbang))
    c = [int(x) for x in str(a)]
    return c

Since the initialization of sbang does not depend on the i in the for loop

CodePudding user response:

The error local variable 'sbang' referenced before assignment means to tell you that you're trying to access the sbang variable without declaring it. Except, you're declaring the variable on line sbang = ''.join(map(str, arr)). So, how could this go wrong?

According to the error, it is possible to reach a line where you access sbang (like if sbang[0] == "0" and len(sbang) > 2:) without it being declared. So, in which case can the line where you declare sbang not be executed? In the case where if i > 9: is always true. So, the next question is. Did you really mean to declare sbang at this location? Perhaps you wanted to do it before or after the loop?

  • Related