while
ループバックそれに戻る、for
ループが完全に実行されるすなわちだけ条件に一致します。したがって、条件が満たされてもプログラムがすぐに終了しないのはこのためです。
しかし、a
の値に条件が満たされなかった場合、b
,c
のコードは無限ループになります。
return
ステートメントはあなたが求めていることを行うため、ここで関数を使用する必要があります。
別に、彼はあなたのプログラムがそのコードブロックの後に任意のコードを持っていない場合、あなたも
sys.exit()
を使用することができ、出口フラグを使用@Sukrit Kalraの
answerから
def func(a,b,c):
for a in range(3,500):
for b in range(a+1,500):
c = (a**2 + b**2)**0.5
if a + b + c == 1000:
print a, b, c
print a*b*c
return # causes your function to exit, and return a value to caller
func(3,4,5)
。
import sys
a = 3
b = 4
c = 5
for a in range(3,500):
for b in range(a+1,500):
c = (a**2 + b**2)**0.5
if a + b + c == 1000:
print a, b, c
print a*b*c
sys.exit() #stops the script
sys.exit
のヘルプ:
>>> print sys.exit.__doc__
exit([status])
Exit the interpreter by raising SystemExit(status).
If the status is omitted or None, it defaults to zero (i.e., success).
If the status is numeric, it will be used as the system exit status.
If it is another kind of object, it will be printed and the system
exit status will be one (i.e., failure).
あなたはここでのポイントの問題を浮動しているつもりだ... ...具体的には、Cはそう浮動小数点#で、丸めたり、キャストしたり、abs(a + b + c-1000)<0.00001(または他のイプシロン)かどうかをチェックします。あるいは私は完全に間違っているかもしれません。 – Foon
'c'は浮動ですが、それは問題ではないようです。プログラムは 'a + b + c = 1000'を見つけて、明らかに' 1000'対 '1000.0'を気にしません。それは時々問題になる可能性があるので、よく分かります。 – caadrider