2008-12-15 293 views
7

我在函數中寫了一個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

回答

12

只是正確地縮進代碼:

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

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

is運營商在Python可能不會做你期望的。取而代之的是:

if numpy.array_equal(tmp,universe_array) is True: 
     break 

我會寫這樣的:

if numpy.array_equal(tmp,universe_array): 
     break 

is操作測試對象的身份,這是一件好事,從平等的完全不同。

0

我會做它用一個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