简体   繁体   English

While循环在Python中没有中断

[英]While Loop Not Breaking In Python

I have a program like this: 我有一个这样的程序:

def read():
    while True:
        for line in temp1:
            if event in line:
                print temp1.next()
            elif date in line:
                print temp1.next()
            elif ending in line:
                print 'End of file'
                break
event = '1'
date = '2'
ending = '3'
temp1 = open('test.txt')

And test.txt looks like this: test.txt看起来像这样:

1
ABC
2
CAB
3

The program outputs this: 程序输出以下内容:

ABC
CAB

And then it goes into an infinite loop. 然后进入无限循环。 Is there a way to fix this? 有没有办法解决这个问题?

Your break statement only breaks out of the for loop (if it's hit). 您的break语句只会跳出for循环(如果命中)。 It doesn't, and indeed, can't break out of the while loop as well. 它确实也不能脱离while循环。 Though I'm not sure what the while loop is there for, since the for loop should iterate over the whole file. 尽管我不确定while循环有什么用,因为for循环应该遍历整个文件。 Since you're already in a function, you can use a return statement to break out of multiple loops (though it would probably be better to just get rid of the extra loop). 由于您已经在函数中,因此可以使用return语句中断多个循环(尽管最好摆脱多余的循环可能会更好)。

在第一个break语句之后的行上添加第二个break语句,但将其与for语句对齐。

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

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