Python 中断并继续功能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13986884/
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
break and continue in function
提问by ThunderEX
def funcA(i):
if i%3==0:
print "Oh! No!",
print i
break
for i in range(100):
funcA(i)
print "Pass",
print i
I know script above won't work. So, how can I write if I need put a function with break or continue into a loop?
我知道上面的脚本不起作用。那么,如果我需要将一个带有 break 或 continue 的函数放入循环中,我该怎么写?
采纳答案by BrenBarn
A function cannot cause a break or continue in the code from which it is called. The break/continue has to appear literally inside the loop. Your options are:
函数不能在调用它的代码中导致中断或继续。break/continue 必须字面上出现在循环内。您的选择是:
- return a value from funcA and use it to decide whether to break
- raise an exception in funcA and catch it in the calling code (or somewhere higher up the call chain)
- write a generator that encapsulates the break logic and iterate over that instead over the
range
- 从 funcA 返回一个值并用它来决定是否中断
- 在 funcA 中引发异常并在调用代码中捕获它(或调用链更高的某个地方)
- 编写一个封装了中断逻辑的生成器并迭代它而不是
range
By #3 I mean something like this:
#3 我的意思是这样的:
def gen(base):
for item in base:
if item%3 == 0:
break
yield i
for i in gen(range(1, 100)):
print "Pass," i
This allows you to put the break with the condition by grouping them into a generator based on the "base" iterator (in this case a range). You then iterate over this generator instead of over the range itself and you get the breaking behavior.
这允许您通过将它们分组到基于“基本”迭代器(在本例中为范围)的生成器中来放置条件中断。然后迭代这个生成器而不是范围本身,你会得到破坏行为。
回答by eumiro
def funcA(i):
if i%3==0:
print "Oh! No!",
print i
return True
else:
return False
for i in range(100):
if funcA(i):
break
print "Pass",
print i
回答by LtWorf
Break won't propagate between functions, you need to put it directly within the loop somewhere.
Break 不会在函数之间传播,你需要将它直接放在循环中的某个地方。
回答by Jakub M.
Elaborating BrenBarns answer: breakfortunatelywill not propagate. breakis to break the current loop, period. If you want to propagate an event, then you should raisean exception. Although, raising the exception to break the loop is a really ugly way to break loops and a nice way to break your code.
详述 BrenBarns 的回答:break幸好不会传播。break是打破当前的循环,周期。如果你想传播一个事件,那么你应该raise是一个例外。虽然,引发异常来中断循环是一种非常丑陋的中断循环方式,也是一种中断代码的好方法。
KISS! The simplest would be to check the condition directly in the loop
吻!最简单的方法是直接在循环中检查条件
def my_condition(x):
return x == 4
for i in xrange(100):
if my_condition(i): break
print i
If, for some reason, you want to propagate an exception, then you use it like this
如果出于某种原因,您想传播异常,那么您可以像这样使用它
# exception example
for i in xrange(100):
if i == 4: raise Exception("Die!")
print i
As mentioned, it is a really uglydesign. Imagine you forget to catch this exception, or you change its type from Exceptionto MyBreakExceptionand forget to change it somewhere in try/excepthigher part of the code...
如前所述,这是一个非常丑陋的设计。想象一下,您忘记捕获此异常,或者您将其类型从to 更改Exception为MyBreakException并忘记try/except在代码较高部分的某处更改它...
The generator example has its merits, it makes your code more functional style(which I presonally adore)
生成器示例有其优点,它使您的代码更具功能性风格(我个人很喜欢)
# generator example
def conditional_generator(n, condition):
for i in xrange(n):
if condition(i):
break
else:
yield i
for i in conditional_generator( 100, my_condition ):
print i
...which is similar to takewhile, mentioned by eumiro
...与takewhileeumiro 提到的类似

