Search code examples
pythonlocal-variables

unboundLocalError: local variable 'loopback' referenced before assignment


my code is as follows:

import openpyxl
from openpyxl import load_workbook

def process(input="Input-Migration Table.xlsx", output_dir="\output"):

 dic_atn = {}
 for row in sheet2.iter_rows(min_col=3,min_row=2,max_col=3,max_row=17):
    for cel in row:
        dic_atn[cel.value] = ""

 for key in dic_atn:
    for i in range(3,6):
        if(sheet1.cell(row=i,column=1).value == key):
            loopback = sheet1.cell(row=i,column=2).value
            break

    for col_config in range(2,11):
     if(sheet3.cell(row=1,column=col_config).value == sheet2.cell(row=row,column=24).value + "-" + sheet2.cell(row=row,column=23).value):

     for i in range(3,78):
      if "<Loopback0>" in sheet3.cell(row=i,column=col_config).value:
       new_loopback = sheet3.cell(row=i, column=col_config).value.replace("<Loopback0>",loopback)

process()

i search from google, it said this error is caused by using a variable out of function, but here, variable "loopback" is defined and used all in function process, why i still get this error ?


Solution

  • The error reference before assignment dictates that the variable has not been created prior to it being called.

    In your case, this is due to the variable only being defined if a specific set of statements are true.

    for i in range(3,6):
            if(sheet1.cell(row=i,column=1).value == key):
                loopback = sheet1.cell(row=i,column=2).value
                break
    

    In the case your if statement never finds a match, loopback is never created as a variable. This cause you to get the error reference before assignment as it was never assigned to begin with.

    You could define the variable separate prior to the if statement, with a default value (or none) if you want to ensure the variable always has a reference.

    loopback = ''
    

    If this isn't a viable fix for your issue, you will need to work on your if statement to ensure it is matched every time you run the application.