Python indentation deters newbies?
Jorge Godoy
godoy at ieee.org
Mon Aug 16 20:11:08 EDT 2004
"beliavsky at aol.com" <beliavsky at 127.0.0.1:7501> writes:
> 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?
For that I'd adopt either the use of exceptions or a flag. ;-)
> It is silly of course, but real-world situations where you want to exit a
> nested loop are not that rare.
>
> 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
>>> n = 4
>>> for i in xrange(1, n):
... for j in xrange(1, n):
... if (i + j > n): exit
... for k in xrange(1, n):
... if ((i + j - k) < 0):
... to_exit = 1
... break
... print i, '\t', j, '\t', k
... if to_exit:
... break
...
1 1 1
1 1 2
2 1 1
2 1 2
2 1 3
3 1 1
3 1 2
3 1 3
>>>
Is your last line (3 1 4) correct? In the expression "3 + 1 - 4 < 0" it
is true, so I think the line should be printed... Should it? (Does the
loop run at least once before evaluating the expression?) I really
haven't paid attention to your code, just "translated" it to the above
python, with the same logic as the previous one. Using exceptions would
give me a finer grained control, I think, but would require more lines
of code.
Be seeing you,
--
Godoy. <godoy at ieee.org>
More information about the Python-list
mailing list