简体   繁体   English

赋值之前引用的局部变量“ statement”

[英]local variable 'statement' referenced before assignment

I am currently creating a while loop in python and I got this problem: 我目前正在python中创建一个while循环,但遇到了这个问题:

local variable 'statement' referenced before assignment

this is my code: 这是我的代码:

    while (statement == True):
        self.headNode = settings.EMPTY_UUID
        try:
            lastNode = Task.objects.get(next = self.headNode)
            self.headNode = lastNode.id
            statement = True
        except:
            statement = False

I am worried if I initialize statement = True before while statement because it might become an infinite loop 我担心如果在while语句之前初始化statement = True,因为它可能会变成无限循环

For instance, this is data of Task.objects: 例如,这是Task.objects的数据:

id    name     next
001   task1    002
002   task2    003
003   task3    000

I would like to get the Id of the root task which should be 001 我想获取根任务的ID,该ID应该为001

The comments already point you to the answer, but here's a (more Pythonic) way to code this: 注释已经为您指出了答案,但这是一种(更Pythonic的)编码方式:

while True:
    self.headNode = settings.EMPTY_UUID
    try:
        lastNode = Task.objects.get(next=self.headNode)
        self.headNode = lastNode.id
        break
    except Task.DoesNotExist:
        break

Even if you'd need the value of statement after the while loop, you don't need the variable: statement is obviously False at that point. 即使您需要在while循环之后使用statement的值,也不需要使用变量: statement在那时显然为False

Note that I've also changed the except statement. 请注意,我还更改了except语句。 It's my assumption you want to catch the error that's raised when the relevant Task object does not exist, but it's generally bad to have a bare, catch-all, except. 我的假设是,您想捕获相关Task对象不存在时引发的错误,但是,除了裸露的包罗万象之外,通常是不好的。

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

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