Python indentation deters newbies?
Roy Smith
roy at panix.com
Mon Aug 16 21:50:23 EDT 2004
"beliavsky at aol.com" <beliavsky at 127.0.0.1:7501> wrote:
> Ok, here is something short but more realistic and IMO not "ugly".
>
> You may want to exit a nested loop when testing if a condition involving
> several variables is met, such as searching for a zero of a multivariate
> function.
>
> In Python you can print i,j,k and exit() when m == 0, but in a larger program
> you may want more control.
>
> program xnest_loop
> ! find a Pythagorean triple
> n = 5
> ido: do i=1,n
> do j=1,n
> ij = i**2 + j**2
> do k=1,n
> m = ij - k**2
> if (m == 0) exit ido
> end do
> end do
> end do ido
> if (m == 0) then
> print*,i,j,k
> else
> print*,"no triple"
> end if
> end program xnest_loop
That's easy (and relatively common). I'd factor out the loop you labled
"ido:" into a separate function, and have your "exit ido" become a
return statement. There's nothing Python-specific about that; I'd use
the same refactoring strategy in C, Fortran, etc. I'm a big fan of
small, easy to understand, functions.
More information about the Python-list
mailing list