PEP-0315--Enhanced While Loop: An idea for an alternative syntax

Andrew Koenig ark at acm.org
Wed Feb 18 00:18:47 EST 2004


PEP 315 suggests that a statement such as

    do:
        x = foo()
    while x != 0:
        bar(x)

be equivalent to

    while True:
        x = foo()
        if x == 0:
            break
        bar(x)

I like the overall idea, but wonder about the extra keyword.  Moreover, if
you see

        x = foo()
    while x != 0:
        bar(x)

you have to read backward to see whether the assignment to x is part of this
statement or part of a previous statement.

I have a proposal for an alternative syntax that solves both of these
problems:

    while:
        x = foo()
    and while x != 0:
        bar(x)

This example actually incorporates two changes:

    1) "while:" is equivalent to "while True:"

    2) "and while <condition>:" is an exit from the middle of the loop,
analogously to PEP 315.

My proposal allows for multiple exits in the obvious way

    while <condition 1>:
        <statements 1>
    and while <condition 2>:
        <statements 2>
    and while <condition 3>:
        <statements 3>
    ...

in which all of the conditions and statements are evaluated in the order
shown until a condition is false, at which point the loop terminates.


It also occurs to me that this notion can be generalized to include "or
while" as well as "and while".  Using "or while" would implement a control
structure that Dijkstra proposed in "A Discipline of Programming".  The idea
would be that

    while <condition 1>:
        <statements 1>
    or while <condition 2>:
        <statements 2>
    or while <condition 3>:
        <statements 3>

would be equivalent to

    while True:
        if <condition 1>:
            <statements 1>
        elif <condition 2>:
            <statements 2>
        elif <condition 3>:
            <statements 3>:
        else:
            break

This notion is still partly baked, if for no other reason than that I'm not
sure how a statement with both "or while" and "and while" clauses should
work.  My first thought is for "and while" to have priority over "or while",
analogously with expressions, but then the following example came to me.
It's the inner loop of a binary search:

    while low < hi:
        mid = (low + hi) // 2;
    and while value < table[mid]:
        high = mid
    or while value > table[mid]
        low = mid

If "and" has higher precedence than "or", this example doesn't work.  So I'm
not sure about its merits -- but I'm mentioning it in case someone else can
improve on it.





More information about the Python-list mailing list