如何停止While循环?

如何停止While循环?

问题描述:

我在函数中写了一个while loop,但不知道如何阻止它。当它不符合最终条件时,循环会永远持续下去。我怎样才能阻止它?如何停止While循环?

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 
+2

问题是你的问题。 “当它不符合最终条件时”。你没有测试最后的条件,你说的是“虽然真实:”。真实将永远是真实的。 – 2008-12-15 14:57:19

+0

感谢您的评论,我只是大约一半知道while while循环..所以不真正知道如何问一个好问题.. – NONEenglisher 2008-12-15 15:02:30

只是正确地缩进代码:

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条件为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 
+0

我也试过这个,但它给出了错误的结果... – NONEenglisher 2008-12-15 14:39:33

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 

is运营商在Python可能不会做你期望的。取而代之的是:

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