在Python中退出while循环 [英] Exit while loop in Python

查看:556
本文介绍了在Python中退出while循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我希望while循环在a + b + c = 1000时退出.但是,使用print语句进行测试表明,它一直持续到for循环完成为止.我试过while True,然后在if语句中设置False,但这会导致无限循环.我认为使用x = 0然后设置x = 1也许可以,但是也可以一直运行直到for循环结束.什么是最优雅,最快的退出方式?谢谢.

In the code below, I'd like the while loop to exit as soon as a + b + c = 1000. However, testing with print statements shows that it just continues until the for loops are done. I've tried while True and then in the if statement set False but that results in an infinite loop. I thought using x = 0 and then setting x = 1 might work but that too just runs until the for loops finish. What is the most graceful and fastest way to exit? Thanks.

a = 3
b = 4
c = 5
x = 0
while x != 1:
    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
                x = 1

推荐答案

仅当控件返回条件时,即完全执行for循环时,while循环才匹配条件.因此,这就是即使满足条件也不会立即退出程序的原因.

The while loop will match the condition only when the control returns back to it, i.e when the for loops are executed completely. So, that's why your program doesn't exits immediately even though the condition was met.

但是,如果abc的任何值都没有满足条件,那么您的代码将以无限循环结束.

But, in case the condition was not met for any values of a,b,c then your code will end up in an infinite loop.

您应该在此处使用一个函数,因为return语句将满足您的要求.

You should use a function here as the return statement will do what you're asking for.

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 Kalra的 answer ,他在其中使用了退出标志,如果您的程序没有使用,也可以使用sys.exit()该代码块之后没有任何代码.

Apart from @Sukrit Kalra's answer, where he used exit flags you can also use sys.exit() if your program doesn't have any code after that code block.

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

这篇关于在Python中退出while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆