[Python-ideas] For/in/as syntax

Chris Angelico rosuav at gmail.com
Fri Mar 3 14:07:53 EST 2017


On Sat, Mar 4, 2017 at 5:56 AM, Matthias Bussonnier
<bussonniermatthias at gmail.com> wrote:
>> *scratches head* How do you break an outer loop without breaking the
>> inner loop? What happens?
>
> Finish running the inner, then breaking the outer. Instead of breaking
> inner and outer.
>
> for i in outer:
>     bk = False
>     for j in inner:
>          if cond:
>              bk = True
>     if bk:
>        break
>
>
> vs
>
> for i in outer:
>     bk = False
>     for j in inner:
>          if cond:
>              bk = True
>              break # this.
>     if bk:
>        break
>
> Sorry if I'm mis expressing myself.

Oh, I see what you mean.

So "breaking the outer loop" really means "flag the outer loop such
that, on next iteration, it will terminate". The trouble is that
that's not exactly what "break" means. Consider:

for i in outer:
    print("Top of outer")
    for j in inner:
        print("Top of inner")
        if cond1:
            break
        if cond2:
            break_outer(inner=False)
        if cond3:
            break_outer(inner=True)
        print("Bottom of inner")
    print("Bottom of outer")

cond1 would print "bottom of outer" and keep loping. cond2 and cond3
should presumably _not_ print "bottom of outer". Should they print
"bottom of inner", though?

Seems like an odd use, though. If I want a multi-step break, I want to
break every step, not just the last one.

ChrisA


More information about the Python-ideas mailing list