更新时间:2023-12-05 19:29:46
一个函数不能在调用它的代码中引起中断或继续.中断/继续必须从字面上出现在循环内.您的选择是:
range
通过#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
这允许您通过将条件分组到基于基本"迭代器(在此情况下为范围)的生成器中来放置条件.然后,您在此生成器上进行迭代,而不是在范围本身上进行迭代,您会得到破坏行为.
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?
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:
range
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.