I'm new to Python and have been doing work converting a few apps[...]
from Perl to Python. I can not figure out the comparable Python
structures for multi-variable for loop control.
I spent a good part of yesterday looking for a way to handle thisOne wonders why... :)
style for loop in Python and haven't been able to find an
appropriate way to handle this control style.
We have this style for loop all over the place and not being able toEven if Python didn't offer a way to write a for loop in a similar
find a similar structure in Python could be a problem. Any pointers
to a Python equivalent structure would be much appreciated
fashion (someone else replied about that already), why should it be a
problem? In general control structures can be rewritten as some other
kind of control structure. For example, this does exactly what your
for loop examples do:
i = 0
j = 0
while i < 5 and j < 10:
print i, j
i += 1
j += 1
Though, this example is silly, as it will always terminate after the
5th iteration of the loop, and there is no need to have j being used
as a control variable... it's termination condition will never be met.
Though the example illustrates the techique, even if the example is
bogus.
Another way is to use functions to modify the values of i and j.
Writing your loops this way, you can have as many control variables as
you need, and your formula for incrementing those control variables
can be as varied as complicated as you can imagine.
def some_increment_function(i):
# Do some complicated processing of i
i = ...
return i
def other_incrjmental_function(j):
# Do some complicated processing of j
j = ...
return j
i = 0
j = 0
while i < 5 and j < 10:
print i, j
i = some_increment_function(i)
j = other_increment_function(j)
And of course, you could also replace the loop terminating conditions
with functions that return a value which can be interpreted as a truth
value. If you wanted to get really crazy, you could even code the
control structure as a recursive function:
def control(i, j):
print i,j
if not (i < 5 or j < 10):
return
else:
control(some_increment_function(i), other_increment_function(j))
Should you really write control structures this way, generally?
Absolutely not (unless you're writing LISP or Scheme :)). But the
point is, even if a given language doesn't have a particular syntactic
element that you're looking for, it's pretty much guaranteed to
provide a way to do what you're trying to do. You just need to stop
thinking about your problem in terms of a particular syntactic
element, and start thinking about it in more general terms of what you
are actually trying to accomplish, and apply whatever syntax (usually
one of several) your language provides to do that.
--
Derek D. Martin
http://www.pizzashack.org/
GPG Key ID: 0x81CFE75D
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (GNU/Linux)
iD8DBQFIgQsAHEnASN++rQIRAlx2AKCGgS2pBb3csYid7H0pgM W0vBYUUQCeJ1rB
lRjw9yBf1UXMLZRU3zn1Irw=
=CVNL
-----END PGP SIGNATURE-----