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

Todd toddrjen at gmail.com
Sun Jun 25 09:25:58 EDT 2017


On Jun 25, 2017 07:58, "Markus Meskanen" <markusmeskanen at gmail.com> wrote:

I'm a huge fan of the do...while loop in other languages, and it would
often be useful in Python too, when doing stuff like:

while True:
    password = input()
    if password == ...:
        break

I've seen the pep 315 which got rejected, and I believe these two
suggestions were mostly focused on:

1.

do ... while <condition>:
    <body>

2.

do:
    <body>
while <condition>

But both were rejected for valid reasons:

1. It makes little sense to have the while at the top, since it might need
to use variables from within the body. That's the whole point of the
do...while loop

2. There's no other syntax like this in Python, where you'd need a closing
unindentation. Also it's using the existing "while" keyword with a
different syntax than the current one

What I'd like to suggest is a different approach, with an existing syntax
found in functions. At first it might sound silly, but I belive it makes
sense after a while:

do:
    <body>

Now bare with me a second, this is similar to function's

def <header>:
    <body>

And similar to how you can exit functions with `return`, you could also
exit the `do` loop with some keyword, such as `until`. This makes it very
similar to how `return` behaves in a function:

do:
    password = input()
    until password == secret_password

Now before you say "but return can be anywhere in the function, and there
can be multiple of them", I suggest we do the same for "until". It would be
like a break, but with a condition:

do:
    password = input('Password: ')
    until password == secret_password

    # This line only gets printed if until failed
    print('Invalid password, try again!')

print('You have successfully signed in!')

The keywords are obviously a subject to change, I've also been tinkering
with repeat/until, do/breakif, repeat/breakon, etc.

Any thoughts, is this complete madness?


The barrier for adding a new keyword is extremely high since anyone using
the name in their code will have their code break.

If we were going to do something like this, I would prefer to use existing
keywords. Perhaps

    break if condition

And we could make "while:" (with no condition) act as "while True:"

But I think the benefit of either of these changes is minimal compared to
what we already have.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170625/656f986a/attachment.html>


More information about the Python-ideas mailing list