
On 6/26/2017 12:41 AM, Nick Coghlan wrote:
On 26 June 2017 at 10:25, Rob Cliffe <rob.cliffe@btinternet.com> wrote:
On 25/06/2017 12:58, Markus Meskanen 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 suggest [...]
do: password = input('Password: ') until password == secret_password
# This line only gets printed if until failed print('Invalid password, try again!')
I don't see any significant advantage in providing an extra Way To Do It. Granted, the "while True" idiom is an idiosyncrasy, but it is frequently used and IMHO intuitive and easy to get used to. Your suggestion doesn't even save a line of code, given that you can write:
while True: password = input('Password:') if password == secret_password: break print('Invalid password, try again!')
Right, this is the key challenge for do-while loops in Python: can you come up with something that's significantly clearer than the current "while True/if/break" pattern?
The biggest weakness of that idiom is that it isn't really explicit in the header line - there's nothing about "while True:" that directly tells the reader "This loop is expected to exit via a break statement".
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
We would then also need 'while not return:'
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"
-- Terry Jan Reedy