break/continue - newbe
Fredrik Lundh
fredrik at pythonware.com
Tue Dec 21 15:44:45 EST 2004
"Ann" <Ann at nospam.invalid> wrote:
> Thanks Jeff, that solves my problem. BTW: is there an easy way to
> break/continue out more than one level?
not really; to continue more than one level, you have to break out of the
inner loop, and make sure the logic in that loop body brings you back to
the top.
to break more than one level, you can:
1) use an exception
class LeaveLoop(Exception): pass
def myfunction():
try:
for a in ...:
for b in ...:
if c:
raise LeaveLoop # break out of both loops
do something
except LeaveLoop:
pass
2) organize your code so you can use return rather than "multi-break"
def myfunction():
calculate()
def calculate():
for a in ...:
for b in ...:
if c:
return
do something
3) use flags
def myfunction():
run = 1
for a in ...:
for b in ...:
if c:
run = 0
if not run:
break
if not run:
break
Solution 2 is almost always the best way to do this; solution 3 is often the worst.
</F>
More information about the Python-list
mailing list