在Python中退出while循环

在Python中退出while循环,第1张

在Python中退出while循环

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 callerfunc(3,4,5)

除了Kalra的答案外,他在其中使用了退出标志,

sys.exit()
如果您的程序在该代码块之后没有任何代码,则也可以使用该标志。

import sysa = 3b = 4c = 5for 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 systemexit status will be one (i.e., failure).


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5647153.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存