Pythonically-expressed nested-loop break?

Bengt Richter bokr at oz.net
Mon Jan 14 03:47:28 EST 2002


Snif. I thought I had an idea worth a comment ;-)
Anyway, perhaps it was not adequately prefaced with
explanation.

The idea was/is to indicate how many loops a break is
breaking by putting a single colon on the line immediately
following the break. The colon is at the level of the
beginning of the outermost loop being broken (and hence
at same level as subsequent code that will be executed
immediately after the break).

You can think of the colon as a kind of vertical ellipsis
pointing down in the proper column to the after-break code,
in easy-to-see symmetry with the beginning of the relevant loop.
This (Pythonic ?;-) use of indentation eliminates the need for
a loop label.

The colon would of course have to be optional in order
not to break (in the other sense ;-) old code.

I thought it was less cluttered than the try-except
approach, etc. Perhaps it was so lean that it was missed?

Anyway, here is the relevant snip (won't work without grammar change):
--
How about using a dedent-level marker on the next line after the break,
e.g., a lone ':' ? Then the eye can just drop down to where it's going.

def btest():
    while 1:
        print 'While1'
        while 2:
            print tab,'While2'
            while 3:
                print tab*2,'While3'
                for i in range(30):
                     r = randint(0,6)
                     print tab*3,'r=',r
                     if r == 1:   break
    :
                     elif r == 2: break
        :
                     elif r == 3: break
            :
            print tab*2,Break3
        print tab,Break2
    print Break1

for test in (1,2,3):
    print 'test',test
    btest()
--



More information about the Python-list mailing list