どのように私は、whileループを停止することができますか?
-
21-08-2019 - |
質問
私は、関数で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
で作成した無限ループを終了することを理解する必要があります。ブレーク条件が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