的while
循环只会匹配时返回到它,即当for
循环完全执行的情况。所以,这就是为什么你的程序即使满足条件也不会立即退出。
但是,如果条件不符合a
,b
,c
的任何值,那么您的代码将以无限循环结束。
您应该使用这里的函数,因为return
语句将完成您要求的操作。
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)
除了@Sukrit卡尔拉的answer,在那里他用出口标志,你也可以使用sys.exit()
如果你的程序没有该代码块之后的任何代码。在sys.exit
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
帮助:
>>> 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(或其他一些epsilon)。否则我可能完全错误。 – Foon
'c'是浮动的,但它似乎并不重要。程序发现'a + b + c = 1000'显然不关心'1000'和'1000.0'。很高兴知道,因为它有时可能会成为问题。 – caadrider