[Python-Dev] PEP 315 - do while

Nick Coghlan ncoghlan at gmail.com
Mon Oct 2 12:48:05 CEST 2006

Hans Polak wrote:
> Hi Nick,
> Yep, PEP 315. Sorry about that.
> Now, about your suggestion 
>      do:
>          <setup code>
>          while <condition>
>          <loop body>
>      else:
>          <loop completion code>
> This is pythonic, but not logical. The 'do' will execute at least once, so
> the else clause is not needed, nor is the <loop completion code>.  The <loop
> body> should go before the while terminator.

This objection is based on a misunderstanding of what the else clause is for 
in a Python loop. The else clause is only executed if the loop terminated 
naturally (the exit condition became false) rather than being explicitly 
terminated using a break statement.

This behaviour is most commonly useful when using a for loop to search through 
an iterable (breaking when the object is found, and using the else clause to 
handle the 'not found' case), but it is also defined for while loops.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-Dev mailing list