[Python-ideas] Updating PEP 315: do-while loops

Larry Hastings larry at hastings.org
Sun Apr 26 04:35:15 CEST 2009

Raymond Hettinger wrote:
> 1) One approach uses the standard do-while name but keeps usual python 
> style formatting by putting the condition at the top instead of the 
> bottom where it is in C and Java: 

I don't like the condition-at-the-top variants, with or without an 
ellipsis.  (At first glance anyway.)

> I haven't found any condition-at-the-end syntax that FeelsRight(tm).
> Probably everyone has an opinion on these, but I don't any think those 
> could be called bike-shedding.  The spelling does matter and hopefully 
> the cleanest solution can be found.

I couldn't quite parse that, but I sure hope it meant "I'm up for yet 
another round of discussion".

I propose we allow an "if" suffix to "break" and "continue".  So I'd 
spell your loop this way:

        j = _int(random() * n)
        continue if j in selected

This would require there be no implied "while True" for a "do" block.  
If you hit the end of the "do" block, without following a continue, 
you'd just leave the block.  So this program would be legal:

    print("well, that was pointless")

It would print two strings then exit.  It would *not* loop.  A little 
unexpected I guess.

On the other hand this form gives a pleasing alternate spelling to 
"while True":


It also provides a dandy spelling for early-exit programming, without 
nesting your ifs, or early return, or throwing an exception, or using 
gotos which thankfully we don't have:

    def user_typed_1_then_2():
           print("enter 1, then 2")
           i = input()
           break if i != '1'
           i = input()
           break if i != '2'
           return True
        print("why do you mistreat me so? it was a simple request!")
        return False

Maybe it's just me, but I think that spelling and those semantics are 
charmingly Pythonic.



More information about the Python-ideas mailing list