[英]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.