question about for cycle
Ant
antroy at gmail.com
Sat Sep 29 06:39:43 EDT 2007
On Sep 29, 11:04 am, "fdu.xia... at gmail.com" <fdu.xia... at gmail.com>
wrote:
...
> What should I do if I want the outer "for" cycle to continue or break ? If I
> put a "continue" or "break" in the inner cycle, it has no effect on the outer
> cycle.
I'd also be interested in the idiomatic solution to this one. I can
see a number of solutions, from the ugly:
for i in range(10):
do_break = True
for j in range(10):
if j == 6:
break
else:
do_break = False
if do_break:
break
This will break the outer loop if the inner loop exited with a break.
Using exceptions:
for i in range(10):
try:
for j in range(10):
print i, j
if j == 6:
raise MyException
except MyException, e:
break # or continue or whatever.
Encapsulating in a function and using return:
def get_value():
for i in range(10):
for j in range(10):
print i, j
if j == 6:
return fn(i, j)
I guess to an extent it would depend on the exact situation as to
which of these is more suitable. Are there any other recommended
solutions to this?
--
Ant...
More information about the Python-list
mailing list