Tuesday, January 10, 2006

FAQTs - Knowledge Base - View Entry - But Python doesn't have a do...while (aka: repeat...until) loop! What do I do?:


C, C++, Pascal, and many other imperative languages have a form of a
loop with the loop test at the bottom, or (equivalently) a loop which is
always executed at least once. Here is how it would be used in C:

/* Skip past the header */
do {
line = file.readOneLine();
} while isHeaderLine( line );

Notice that if we were to translate this into a while loop (test-at-top
loop) then the data preparation step would have to be repeated:

/* Skip past the header */
line = file.readOneLine();
while( isHeaderLine(line) ) {
line = file.readOneLine();
}

Repeating it is bad style, and it gets quite bad if there's more than a
single line (exception handling, for instance). So what is a programmer
to do in Python, which has only the test-at-top style of loops? Here it is:

# Skip past the header
while 1:
line = file.readOneLine();
if not isHeaderLine( line ): break

0 Comments:

Post a Comment

<< Home