clever exit of nested loops

Mark Lawrence breamoreboy at gmail.com
Wed Sep 26 15:06:09 EDT 2018


On 26/09/18 08:50, vito.detullio at gmail.com wrote:
> Hi
> Today I've added a couple of lines in my source code, and I'm very ashamed of it.
> it "runs", and I know what it does (for now), but it's "too clever".
> I have "abused" the "else" clause of the loops to makes a break "broke" more loops
> 
> 
>      for i in range(10):
>          print(f'i: {i}')
>          for j in range(10):
>              print(f'\tj: {j}')
>              for k in range(10):
>                  print(f'\t\tk: {k}')
> 
>                  if condition(i, j, k):
>                      break
> 
>              else:        # if there weren't breaks in the inner loop,
>                  continue # then make anoter outer loop,
>              break        # else break also the outer one
> 
>          else:
>              continue
>          break
> 
> the "magic" is in that repeated block... it's so convoluted to read... still it's very useful to omit "signals" variables or the need to refactor it in a function with an explicit return or other solutions.
> 
> is there any chance to extends the python grammar to allow something like
> 
> 
>      for i in range(10) and not break:
>          print(f'i: {i}')
>          for j in range(10) and not break:
>              print(f'\tj: {j}')
>              for k in range(10):
>                  print(f'\t\tk: {k}')
> 
>                  if condition(i, j, k):
>                      break
> 
> 
> with the semantics of break a loop if an inner loop "broke"?
> 
>   
> 

To me the Ned Batchelder presentation 
https://www.youtube.com/watch?v=EnSu9hHGq5o "Loop like a Native" is the 
definitive way on how to deal with loops in Python.

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence




More information about the Python-list mailing list