[Tutor] what i miss is a C style for loop

Magnus Lycka magnus@thinkware.se
Mon, 21 Oct 2002 14:34:34 +0200


At 23:53 2002-10-21 +1300, Thomi Richards wrote:
>yep, thats right, i live those C style for loops. they are compact, and
>easy to use, once you get the hang of it..

I'll quote Yoda: "You must unlearn what you have learned!" ;)

Each time I try to program Perl I'm painfully made aware
that I really have to follow the style and idioms of the
programming language I use. My pythonesque perl programs
won't work... C style python programs won't be good python
programs.

Could you please post some examples of how you typically
use for loops, in some kind of context, and let us show
how these things are normally solved in python?

I assume that Guido's reasoning was along the lines that
C style for loops are just a shorthand for while loops.

for (init; test; update) {block;}

is basically the same thing as

init;
while (test) {block; update;}

It doesn't really add anything substantial to the language,
and it's even ambiguous, at least in C++. (Are declarations
in the for statement inside or outside the loop?)

There are also common off-by-one errors that appear with
C/C++/Java for loops. As you said: "once you get the hang
of it"...

The python for loop typically eliminate such problems
by iterating over a sequence instead of providing index
numbers. The range and xrange functions provide a tool
for looping over integer ranges, with whatever stepping
you like. You can loop directly over the lines in a file,
not needing to worry about EOF etc.

Some people are confused by range(x) stopping short of x,
but it's completely consistent with other parts of the
language such as indexing and slicing, so understanding
that part of python is a general issue in the language.


--=20
Magnus Lyck=E5, Thinkware AB
=C4lvans v=E4g 99, SE-907 50 UME=C5
tel: 070-582 80 65, fax: 070-612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se