繁体   English   中英

在 Python 中退出 while 循环

[英]Exit while loop in Python

在下面的代码中,我希望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

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

但是,如果abc任何值都不满足条件,那么您的代码将最终陷入无限循环。

您应该在此处使用一个函数,因为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 Kalra 的回答(他使用退出标志的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

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

如果你不想创建一个函数(你应该在这种情况下参考 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

您可以将内部代码重构为一个函数并使用 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

看看这个问题。

问题是,即使在 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

您可以使用 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

您可以使用try/excep包装并在满足条件时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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM