return in loop for ?

Magnus Lycka lycka at carmen.se
Thu Nov 24 19:07:15 CET 2005


Mike Meyer wrote:
> This isn't noticably different than the original. Of course, if you
> want to *do* something after the for loop, you have to test
> the conditional again (or use a flag variable):
> 
> def f():
>     for i in range(20):
>         if i > 10: break
>         inloop()
>     if not (i > 10):
>        afterloop()
>     return

Nope. Use for-else, like this:

def f():
     for i in range(20):
         if i > 10: break
         inloop()
     else:
        afterloop()
     return


In practice, a good reason to follow Knuth rather than Dijkstra,
and allow multiple exits, is that the more levels of indentation
we have, the more difficult it is to follow the code.

Flat is better than nested...

With multiple exits, we can typically often avoid nested else
blocks etc, and get a much more linear program flow, where
error cases etc lead to a premature exits, and the normal,
full flow just runs straight from top to bottom in a function.



More information about the Python-list mailing list