caa*_*der 6 python loops while-loop
在下面的代码中,我希望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
Run Code Online (Sandbox Code Playgroud)
在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 caller
func(3,4,5)
Run Code Online (Sandbox Code Playgroud)
除了@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
Run Code Online (Sandbox Code Playgroud)
帮助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).
Run Code Online (Sandbox Code Playgroud)
如果您不想创建一个函数(在这种情况下您应该这样做并参考 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
42776 次 |
| 最近记录: |