[Python-ideas] A suggestion for a do...while loop

Chris Angelico rosuav at gmail.com
Mon Jun 26 02:14:27 EDT 2017


On Mon, Jun 26, 2017 at 2:41 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> If we wanted to allow that to be expressed literally, we could
> probably special case the "while not break" keyword sequence as a do
> loop:
>
>     while not break:
>         # Setup
>         if condition: break
>         # Loop continuation
>
> That more explicit declaration of intent ("The code in the loop body
> will conditionally break out of this loop") would allow a couple of
> things:
>
> - the compiler could warn that an else clause attached to such a loop
> will never execute (technically it could do that for any expression
> that resolves to `True` as a constant)
> - code linters could check the loop body for a break statement and
> complain if they didn't see one
>
> Logically, it's exactly the same as writing "while True:", but whereas
> that spelling suggests "infinite loop", the "while not break:"
> spelling would more directly suggest "terminated inside the loop body
> via a break statement"
>

What I like doing is writing these loops with a string literal as the
"condition". It compiles to the same bytecode as 'while True' does,
and then you can say what you like in the string. (An empty string
would be like 'while False', but there's no point doing that anyway.)
So, for example:

while "password not correct":
    password = input('Password:')
    if password == secret_password: break
    print('Invalid password, try again!')

ChrisA


More information about the Python-ideas mailing list