Home > Software engineering >  Python, variable defined in loop, is not defined
Python, variable defined in loop, is not defined

Time:02-10

Hello currently I am debugging some code I found on Github to get it to work I have seemed to fix most things but one error still persists when I get to this for loop.

# Create a dataframe with a list of unique P-statements
P = pandas.DataFrame(Plist, columns = {'Code'})
Punique = P[P.Code!=''].drop_duplicates()

codes = Punique['Code']
for code in codes:
    statements = [' '.join([Pstatements[solo] for solo in re.findall(soloPpattern,code)]) for code in Punique['Code']]
Precautions = dict(zip(codes, statements))

The code is taken from https://github.com/arnauddevie/Hazard-Assessment-CAS-Lookup/blob/master/hazard_assessment_cas_lookup.py

Thank you very much.

P.s. NameError: name 'statements' is not defined Sorry completely forgot to add the error.

CodePudding user response:

statements = []  //Add this line before the for loop.
for code in codes:
        statements = [' '.join([Pstatements[solo] for solo in re.findall(soloPpattern,code)]) for code in Punique['Code']]
Precautions = dict(zip(codes, statements))

But why codes is empty you should debug deeply.

CodePudding user response:

Initialize the list before the for loop, and add items in it in the for loop:

statements = []
for code in codes:
    statements.append(' '.join([Pstatements[solo] for solo in re.findall(soloPpattern,code)) for code in Punique['Code']])
Precautions = dict(zip(codes, statements))
  •  Tags:  
  • Related