1

I know there are quite a few "python scope questions" here but I am VERY rusty with python and I am really confused about a "UnboundLocalError" problem I keep getting. I have read that 'for' loops do not have a contained scope yet my code seems to be acting in that way... My code looks like this:

`
...
for b in blocks[:]:
    if b.contains(CONSTANT_NUM):                                    
        r = b.split(CONSTANT_NUM+2)
        if r: blocks.append(r)
        Foo= struct.unpack('<H', b.data)[0]
        Bar = Foo
...
print("Foo: 0x%x" % (Foo))
`

Whenever I run this, I get the error "UnboundLocalError: local variable 'Foo' referenced before assignment". When I instead try and print Bar I get the same error. Why is the assignment not being carried outside of the 'for' loop?

Beau R
  • 53
  • 5
  • This will happen if the assignment is never execute, or in other word if the `if` expression never becomes True. – Klaus D. Nov 15 '19 at 19:32
  • 1
    Perhaps ‘b.contains ...’ was never true. – quamrana Nov 15 '19 at 19:32
  • 2
    Does this answer your question? [Error Code: UnboundLocalError: local variable referenced before assignment](https://stackoverflow.com/questions/17560736/error-code-unboundlocalerror-local-variable-referenced-before-assignment) – ufoxDan Nov 15 '19 at 19:33
  • If you declare a variable inside a for loop you will not be able to access outside that for loop. – Bayleef Nov 15 '19 at 20:05
  • @ufoxDan no, the error in that other question has a different cause. – Don Hatch Nov 15 '19 at 21:45

3 Answers3

4

It could be very likely that your loop never went into the if statement and hence Foo was never initialized. You need to initialize it before the loop just to make sure that if that conditional is never met, you have something to print.

2

In your case, if the 1st if condition is failing, then the compiler won't reach the Foo = ... statement. Which will result in the error you are getting now.

0

The error indicates that at the time of checking the variable foo you have not yet initialized. you should initialize it before the loop.

k2a
  • 71
  • 1
  • 6