在 Python 中退出 while 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16656313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:17:49  来源:igfitidea点击:

Exit while loop in Python

pythonloopswhile-loop

提问by caadrider

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

在下面的代码中,我希望while循环在a+ b+ c= 时立即退出1000。但是,使用print语句测试表明它会一直持续到for循环完成。我已经尝试过while True然后在if语句集中,False但这会导致无限循环。我认为使用x = 0然后设置x = 1可能会起作用,但这也只会运行直到for循环完成。最优雅、最快捷的退出方式是什么?谢谢。

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

采纳答案by Ashwini Chaudhary

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

while循环将只匹配条件时,当控制返回到它,即for循环完全执行。因此,这就是为什么即使满足条件,您的程序也不会立即退出的原因。

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

但是,如果条件没有被满足的任何值abc那么你的代码将在一个无限循环结束。

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

您应该在此处使用一个函数,因为该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)

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.

除了@Sukrit Kalra 的回答,在他使用退出标志的地方,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

help on sys.exit:

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

回答by pascalhein

You can refactor the inner code into a function and use return to exit:

您可以将内部代码重构为一个函数并使用 return 退出:

def inner():
    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 False
    return True

while inner():
    pass

Have a look at thisquestion.

看看这个问题。

回答by David Ding

The problem is, even though you set x=1 when a+b+c==1000, you do not break out of the two for loops when that condition is met, and so the while loop doesn't know that x==1 until both for loops finish. To avoid this problem, you can add explicit break statements to the for loops (and as Sukrit Kalra points out, the while loop becomes unnecessary).

问题是,即使在 a+b+c==1000 时设置 x=1,当满足该条件时也不会跳出两个 for 循环,因此 while 循环不知道 x== 1 直到两个 for 循环完成。为了避免这个问题,你可以在 for 循环中添加明确的 break 语句(正如 Sukrit Kalra 指出的,while 循环变得不必要)。

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

回答by Israel Unterman

You can wrap with try/excepand raisewhen the condition is met.

当条件满足时,您可以用try/excepand换行raise

class FinitoException(Exception):
    pass

a = 3
b = 4
c = 5
x = 0
try:
  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
              raise FinitoException()
except FinitoException:
    return # or whatever

回答by Sukrit Kalra

If you don't want to make a function ( which you should and refer to Ashwini's answer in that case), here is an alternate implementation.

如果你不想创建一个函数(你应该在这种情况下参考 Ashwini 的回答),这里是一个替代实现。

>>> x = True
>>> 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 = False
                 break
         if x == False:
            break
200 375 425.0
31875000.0

回答by TyCharm

You could use a break statement:

您可以使用 break 语句:

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
                break