中断并继续功能 [英] break and continue in function
问题描述
def funcA(i):
if i%3==0:
print "Oh! No!",
print i
break
for i in range(100):
funcA(i)
print "Pass",
print i
我知道上面的脚本不起作用.那么,如果我需要将一个带有 break 或 continue 的函数放入循环中,我该怎么写?
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 必须字面上出现在循环内.您的选择是:
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:
- 从funcA返回一个值并用它来决定是否中断
- 在 funcA 中引发异常并在调用代码(或调用链的更高位置)中捕获它
- 编写一个封装中断逻辑的生成器,并在
range
上迭代它
#3 我的意思是这样的:
By #3 I mean something like this:
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.
这篇关于中断并继续功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!