statements in control structures (Re: Conditional Expressions don't solve the problem)

Huaiyu Zhu huaiyu at gauss.almadan.ibm.com
Tue Oct 23 21:32:46 EDT 2001


On Tue, 23 Oct 2001 23:09:01 +0200, Markus Schaber <use-net at schabi.de> wrote:
>
>> - presumably multiple "while" parts would be allowed.
>
>I don't see the sense behind this, could you give me an example where this would be useful and what semantics you have in mind?
    
    do:
       line = f.readline()
    while not line.is_end():
       ...
    while count < max:
       ...
    
If it's in the middle of a loop, it should be able to replace the 'if not:
break' idiom, which could occur multiple times.

>> One small problem is whether the while part should be indented or not:
>> It is more like a "case" statement (with fall through) than an "elif"
>> statement.
>
>You mean that while is more indented than do, and the statements are further indented? I'm afraid this would be too complex for programmers and parsers to handle.
>
>if/elif/else use same indentation level, also try/except/finally use the same indentation level.

But those branches are exclusionary.  The above example is like
    
    while 1:
        ...
        if line.is_end(): break
        ...
        if count >= max: break
        ...

The different blocks in the body are actually segments in one flow.  So the
spelling should be something like (notice no colon after while)
    
    loop:
        ...
        while not line.is_end()
        ...
        while count < max
        ...

and the current while-statement could be spelt as
    
    loop:
        while ...
        ...
    
The 'until' structure proposed by someone would be spelt as
    
    loop:
        ...
        while not ...

This of course would change the meaning of the keyword, so it's not going to
happen.

BTW, just to show that there are more variations on this topic than
currently being discussed, there was recently a thread about prime
algorithms.  I found that the clearest pseudocode would look like

    def getprimes(x):
        primes = []
        for n in range(2, x):
            for p in primes while p*p <= n:
                if n % p == 0: break
            else: primes.append(n)
        return primes
    
I have not been able to translate this into Python without using duplicate
code or temporary variables - not sure about iterators as I haven't tried
2.2 yet.

This would also be handy for list comprehensions.  In analogy to
    
    >>> a = range(10)
    >>> [x for x in a if (x-5)**2 > 4]
    [0, 1, 2, 8, 9]
    
we could have
    
    >>> a = range(10)
    >>> [x for x in a while (x-5)**2 > 4]
    [0, 1, 2]


Thinking about this - perhaps the real problem is multiple exits for loops -
at least one normal end to loop and another abnormal end.

Huaiyu



More information about the Python-list mailing list