如何停止 While 循环? [英] How can I stop a While loop?
问题描述
我在一个函数中写了一个 while 循环
,但不知道如何停止它.当它不满足其最终条件时,循环将永远运行.我怎样才能阻止它?
I wrote a while loop
in a function, but don't know how to stop it. When it doesn't meet its final condition, the loop just go for ever. How can I stop it?
def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is a another function
period+=1
if numpy.array_equal(tmp,universe_array) is True:
break #i want the loop to stop and return 0 if the
#period is bigger than 12
if period>12: #i wrote this line to stop it..but seems it
#doesnt work....help..
return 0
else:
return period
推荐答案
只需正确缩进代码:
def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is a another function
period+=1
if numpy.array_equal(tmp,universe_array) is True:
return period
if period>12: #i wrote this line to stop it..but seems its doesnt work....help..
return 0
else:
return period
您需要了解示例中的 break
语句将退出您使用 while True
创建的无限循环.所以当中断条件为 True 时,程序将退出无限循环并继续执行下一个缩进块.由于您的代码中没有后续块,因此函数结束并且不返回任何内容.因此,我通过将 break
语句替换为 return
语句来修复您的代码.
You need to understand that the break
statement in your example will exit the infinite loop you've created with while True
. So when the break condition is True, the program will quit the infinite loop and continue to the next indented block. Since there is no following block in your code, the function ends and don't return anything. So I've fixed your code by replacing the break
statement by a return
statement.
按照你的想法使用无限循环,这是最好的写法:
Following your idea to use an infinite loop, this is the best way to write it:
def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is a another function
period+=1
if numpy.array_equal(tmp,universe_array) is True:
break
if period>12: #i wrote this line to stop it..but seems its doesnt work....help..
period = 0
break
return period
这篇关于如何停止 While 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!