python将'while循环'和'for循环'结合起来遍历一些数据 [英] python combine 'while loop' with 'for loop' to iterate through some data
问题描述
我正在尝试将 while
循环与 for
循环结合起来遍历某个列表,但我得到了无限循环.我的代码:
I am trying to combine a while
loop with a for
loop to iterate through some list but I am getting infinite loops. My code:
l=[0,2,3,4]
lo=0
for i in range(len(l)):
while (True):
lo+=1
if lo+l[i]>40:
break
print(lo)
此代码导致无限循环.当条件 lo+ l[i]
大于 40 时,我想要一个输出;它应该停止循环并打印最终的
This code results in an endless loop. I want an output when the condition lo+ l[i]
is greater than 40; it should stop looping and print the final lo
output as result. I tried every method of indentation of the print line, but could not get what I wanted. Thanks in advance.
推荐答案
你得到无限循环,因为你编写无限循环.您可能认为 break
语句会以某种方式神奇地"知道您不仅要结束 for 循环,还要结束 while 循环.但是 break
总是只会中断一个循环——最里面的一个.所以这意味着您的代码实际上是这样做的:
You get infinite loop because you wrote the infinite loop. You've probably thought that the break
statement will somehow "magically" know that you don't want to end just the for loop, but also the while loop. But break
will always break only one loop - the innermost one. So that means that your code actually does this:
while (True): # <- infinite while loop
lo += 1
for i in range(len(l)): # <- for loop
if not l[i] < 3:
break # <- break the for loop
print(lo)
# while loop continues
如果你想结束两个循环,你必须明确地做——例如,您可以使用布尔变量:
If you want to end both loops, you have to do it explicitly - for example, you can use a boolean variable:
keep_running = True
while (keep_running):
lo += 1
for i in range(len(l)):
if not l[i] < 3:
# this will effectively
# stop the while loop:
keep_running = False
break
print(lo)
这篇关于python将'while循环'和'for循环'结合起来遍历一些数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!