栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Python中退出while循环

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在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).


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/641364.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号