faqts : Computers : Programming : Languages : Python : Language and Syntax

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

90 of 104 people (87%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

But Python doesn't have a do...while (aka: repeat...until) loop! What do I do?

Jun 21st, 2002 06:10
Michael Chermside, Michael Soulier, Sean 'Shaleh' Perry


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