question about for cycle

Peter Otten __peter__ at web.de
Sat Sep 29 07:36:26 EDT 2007


Ant wrote:

> 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

Here's a variant that doesn't need the flag

>>> inner = "abc"
>>> outer = "xbz"
>>> for i in outer:
...     for k in inner:
...             if i == k:
...                     print "found", i
...                     break
...     else:
...             print i, "not found"
...             continue
...     break
... 
x not found
found b
 
but I usually prefer a helper function like this

> def get_value():
>   for i in range(10):
>     for j in range(10):
>        print i, j
>        if j == 6:
>           return fn(i, j)

or this:

>>> def f(i, inner):
...     for k in inner:
...             if i == k:
...                     print "found", i
...                     return True
... 
>>> for i in outer:
...     if f(i, inner):
...             break
...     print i, "not found"
... 
x not found
found b

Peter



More information about the Python-list mailing list