简体   繁体   中英

Python variable declared in 'for' loop not seen outside of loop

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?

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM