clever exit of nested loops

Christian Gollwitzer auriocus at gmx.de
Thu Sep 27 05:13:07 EDT 2018


Am 26.09.18 um 12:28 schrieb Bart:
> On 26/09/2018 10:10, Peter Otten wrote:
>>      class Break(Exception):
>>          pass
>>
>>      try:
>>          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):
>>                          raise Break
>>      except Break:
>>          pass
>>
> 
> For all such 'solutions', the words 'sledgehammer' and 'nut' spring to 
> mind.
> 
> Remember the requirement is very simple, to 'break out of a nested loop' 
> (and usually this will be to break out of the outermost loop). What 
> you're looking is a statement which is a minor variation on 'break'. 

Which is exactly what it does. "raise Break" is a minor variation on 
"break".

> Not 
> to have to exercise your imagination in devising the most convoluted 
> code possible.

To the contrary, I do think this solution looks not "convoluted" but 
rather clear. Also, in Python some other "exceptions" are used for a 
similar purpose - for example "StopIteration" to signal that an iterator 
is exhausted. One might consider to call these "signals" instead of 
"exceptions", because there is nothing exceptional, apart from the 
control flow.

	Christian





More information about the Python-list mailing list