Search code examples
pythonpandasjupyter-notebookspyder

local variable 'result" referenced before assignment


I'm trying to import my calculator created using spyder on pandas Jupyter but received the above error. Tried using else: but still getting the error.

Heres my spyder code.

import pandas as pd

def calc_convert(Unit,result):

    if Unit == 'mg/g':
        testr = result*0.100
    elif Unit == 'g/day':
        testr = result*100
    elif Unit == 'g/g':
        testr = result*0.100*1000
    else:
        testr = result*1

    return testr

here's my pandas jupyter code

lst_test = []
for index, row in test.iterrows():
     lst_test.append(calc_convert(row['Unit'],row['result']))

test['converted'] = pd.Series(lst_test,index=test.index)

display(test)

This is the traceback error from Jupyter pandas


---------------------------------------------------------------------------

UnboundLocalError                         Traceback (most recent call last)

<ipython-input-170-5dfe9296da1e> in <module>

      1 lst_test = []

      2 for index, row in test.iterrows():

----> 3     lst_test.append(calc_convert(row['Unit'], row['result']))

      4

      5 test['converted'] = pd.Series(lst_test, index=test.index)

 

     17   elif Unit == 'g/g':

     18       testr = result*0.100*1000

---> 19   else:

     20       testr = result*1

     21

 

UnboundLocalError: local variable 'testr' referenced before assignment


Solution

  • Restarting the Kernel worked. Thank you everyone for your inputs.