Python indentation deters newbies?
Jeff Shannon
jeff at ccvcorp.com
Mon Aug 16 22:56:16 EDT 2004
beliavsky at aol.com wrote:
>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.
>
>
In this case, I can see several Pythonic ways of doing this.
One would be to use an exception. While exceptions are not considered
good control structures in other languages, they *are* considered
acceptable (and even desirable) in Python.
Another way would be to wrap the nested loops inside a function, and
simply return the appropriate triple from that function as soon as you
find it.
An improvement on that would be to replace your return statement with a
yield. Suddenly you've got a generator that'll find a whole series of
Pythagorean triples!
def pyth_triple(max):
max += 1 # to simplify range() calls later
for i in range(1,max):
for j in range(1,max):
ij = i**2 + j**2
for k in range(1,max):
m = ij - k**2
if m == 0:
yield (i, j, k)
for triple in pyth_triple(10):
print triple
(3, 4, 5)
(4, 3, 5)
(6, 8, 10)
(8, 6, 10)
For my money, that's cleaner/clearer than the Fortran version.
Jeff Shannon
Technician/Programmer
Credit International
More information about the Python-list
mailing list