Python indentation deters newbies?

Roy Smith roy at panix.com
Tue Aug 17 01:42:51 CEST 2004


In article <41214271_1 at 127.0.0.1>,
 "beliavsky at aol.com" <beliavsky at 127.0.0.1:7501> wrote:

> Jorge Godoy <godoy at ieee.org> wrote:
> 
> >Just an attempt and trying to keep it like your code. 
> 
> Thanks. My code did not correctly illustrate breaking out of more than one
> level of loop. How would the following code be translated to Python?

Ugh.  This is a truly ugly scenario.  You've got three nested loops, 
with each inner loop having a break out of both itself and the 
immediately containing loop.  Does this correspond to some real-world 
algorithm, or is it just a diabolical scenario invented for the example?

The bottom line is that this is really ugly and convoluted logic, and as 
such is probably going to be ugly and convoluted no matter what language 
you write it in.  Unless I don't understand what your code does, I don't 
see any way to write it in Python which won't be as ugly or uglier as 
your original.

> It is silly of course, but real-world situations where you want to exit a
> nested loop are not that rare.

Yes, there are occasions where you want nested loops (even three deep), 
and need to break out of the innermost one.  But I've never seen 
anything quite as complex as the scenario you set up here.

What I usually do when I've got a deeply nested loop like that is to 
factor it out into its own function, and let the return statement act 
like a multi-level break.  Something like:

def foo (n):
   """Return the first (i, j, k) triple that meets some
   condition.  Return None if the condition is never met."""
   for i in range (n):
      for j in range (n):
         for k in range (n):
            if condition:
                 return i, j, k
   return None




> 
> program xnest_loop
> ! illustrate breaking a nested loop
> integer :: i,j,k,n
> n = 4
> ido: do i=1,n
>    jdo: do j=1,n
>       if (i+j > n) exit ido
>       do k=1,n
>          if (i+j-k < 0) exit jdo
>          print*,i,j,k
>       end do
>    end do jdo
> end do ido
> end program xnest_loop
> 
> output:
>  1 1 1
>  1 1 2
>  2 1 1
>  2 1 2
>  2 1 3
>  3 1 1
>  3 1 2
>  3 1 3
>  3 1 4
> 
> 
> 
> 
> ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet 
> News==----
> http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 
> Newsgroups
> ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption 
> =---



More information about the Python-list mailing list