Able to access variable inside one if-statement but not other

Viewed 17

Here's a snippet from my code and it's weird why I'm able to access the variable named 'calBegPoint ' inside 3rd if statement but not the second.

if graph != None:
                for trace in graph['data']:
                        if 'LSR(' in trace['name']:
                                calBegPoint = trace['x'][0]      #Statement 1
                        if '% change' in trace['name']:
                                print(calBegPoint)       #Statement 2
                        if 'LSR Extended' in trace['name']:
                                print(calBegPoint)        #Statement 3

When I run this code, I get the following error on Statement 2 but, if I comment it, I do not get the error for Statement 3. To solve, this problem, I tried declaring calBegPoint= "Hi" before the entire snippet. With that I did not get the error but, the value printed on Statement 2 was 'Hi' and not the one I calculated.

I've been trying to debug it for hours. Any direction/pointer will be appreciated

UnboundLocalError: local variable 'calBegPoint' referenced before assignment
1 Answers

The error message tries to tell you that you use calBegPoint before defining it.

In your case, the first execution of the second or third if statement lies before the first execution of the first if statement.

Related