简体   繁体   English

Python 在“for”循环中声明的变量在循环外看不到

[英]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.我知道这里有很多“python scope 问题”,但我对 python 非常生疏,而且我对不断遇到的“UnboundLocalError”问题感到非常困惑。 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'循环没有包含 scope 但我的代码似乎以这种方式运行......我的代码如下所示:

`
...
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".每当我运行它时,我都会收到错误“UnboundLocalError:分配前引用的局部变量'Foo'”。 When I instead try and print Bar I get the same error.当我尝试打印 Bar 时,我得到了同样的错误。 Why is the assignment not being carried outside of the 'for' loop?为什么赋值不在“for”循环之外进行?

It could be very likely that your loop never went into the if statement and hence Foo was never initialized.您的循环很可能从未进入 if 语句,因此 Foo 从未初始化。 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.在您的情况下,如果第一个if condition失败,则编译器将不会到达Foo =...语句。 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.该错误表明在检查变量 foo 时您尚未初始化。 you should initialize it before the loop.你应该在循环之前初始化它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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