在Python中退出while循环 [英] Exit while loop in Python
问题描述
在下面的代码中,我希望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.
但是,如果a
,b
,c
的任何值都没有满足条件,那么您的代码将以无限循环结束.
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屋!