Pythonically-expressed nested-loop break?

Bengt Richter bokr at oz.net
Tue Jan 15 04:34:51 EST 2002


On Tue, 15 Jan 2002 08:54:57 +1100, "Delaney, Timothy" <tdelaney at avaya.com> wrote:

>> From: bokr at oz.net [mailto:bokr at oz.net]
>> 
>> 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()
>
>I'm not intending to be insulting, but I ignored this suggestion when it
>first came up in the hopes that it would just quietly disappear.
>
My goal was an uncluttered syntax to accomplish the ends apparently already
(at least tentatively) sought, i.e., breaking out of a controlled number of
nested loops with one break action. Personally, minimizing structural changes,
I would probably implement the above functionality something like
--
def btest():
  lv=1
  while lv >= 1:
      print 'While1'
      lv = 2
      while lv >= 2:
          print tab,'While2'
          lv = 3 
          while lv >= 3:
              print tab*2,'While3'
              for i in range(30):
                  r = randint(0,6)
                  print tab*3,'r=',r
                  if r == 1:
                      lv=0  # breaks loop 3, 2 & 1
                      break
                  elif r == 2:
                      lv=1  # breaks loop 3 & 2
                      break
                  elif r == 3:
                      lv=2  # breaks loop 3
                      break
              if lv!=3: print tab*lv,'Break',lv+1
--


>One of the big wins with Python is the lack of block delimiters. This is
>essentially creating block delimiters, but worse - they are optional and
>only used for some blocks. This is a Bad Thing(TM).
>
Well, I'd say there are blocks, and they are delimited. Just not by the usual glyphs.
And my colons don't *delimit* blocks, they indicate ways out of blocks ;-)

>Additionally IM(NS)HO, it is incredibly ugly. I mean *really* *really* ugly.
>It's kind of like comparing it to space. Space is big ... (see HHGTTG for
>the rest).
Shux, 'twarn't nothin' ;-)




More information about the Python-list mailing list