题
我写一个函数while loop
,但不知道如何阻止它。当它不符合它的最终状态,循环只是去,直到永远。我怎样才能阻止它?
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
创建的无限循环。所以,当断条件为真,程序将退出无限循环,并继续到下一个缩进块。因为在你的代码没有后续块,函数结束,不返回任何东西。所以,我通过一个break
声明替换return
声明固定你的代码。
按照你的想法用一个无限循环,这是写它的最佳方式:
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
其他提示
def determine_period(universe_array):
period=0
tmp=universe_array
while period<12:
tmp=apply_rules(tmp)#aplly_rules is a another function
if numpy.array_equal(tmp,universe_array) is True:
break
period+=1
return period
在Python中的is
运营商可能不会做你期望的。取而代之的是:
if numpy.array_equal(tmp,universe_array) is True:
break
我会写这样的:
if numpy.array_equal(tmp,universe_array):
break
在is
操作者测试对象的身份,这点是从平等很大的不同。
我会使用for循环做,如下所示:
def determine_period(universe_array):
tmp = universe_array
for period in xrange(1, 13):
tmp = apply_rules(tmp)
if numpy.array_equal(tmp, universe_array):
return period
return 0
不隶属于 StackOverflow