Python indentation deters newbies?

Paul Rubin http
Tue Aug 17 01:51:18 CEST 2004


"beliavsky at aol.com" <beliavsky at 127.0.0.1:7501> writes:
> 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?
> It is silly of course, but real-world situations where you want to exit a
> nested loop are not that rare.

They're really not all that common.

> ido: do i=1,n
>    jdo: do j=1,n
>       if (i+j > n) exit ido
>       ...

Well, you could do it with try/raise, like
   try:
     for i in xrange(1,n+1):
       for j in xrange(1, n+1):
         if i+j > n: raise 'foo'
       ...
   except 'foo': 
     ...

but more normally you'd just say
   for i in xrange(1,n+1):
      for j in xrange(1, n-i+1):
          ...



More information about the Python-list mailing list