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:
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.
Elaborating BrenBarns answer:
break
fortunately will not propagate.break
is to break the current loop, period. If you want to propagate an event, then you shouldraise
an 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.KISS! The simplest would be to check the condition directly in the loop
If, for some reason, you want to propagate an exception, then you use it like this
As mentioned, it is a really ugly design. Imagine you forget to catch this exception, or you change its type from
Exception
toMyBreakException
and forget to change it somewhere intry/except
higher part of the code...The generator example has its merits, it makes your code more functional style (which I presonally adore)
...which is similar to
takewhile
, mentioned by eumiroBreak won't propagate between functions, you need to put it directly within the loop somewhere.