Skip to content

@metaperl /python-do-while.md
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Python lacks a do-while. Here is my preferred solution

Python lacks a do-while loop. So here is how I like to emulate one:

def do_while():
    result = do_something()
    if result:
        return True
    else:
        return do_while()

And I figured that Python is tail-recursive and this would not blow the stack. Am I right?

@rob-smallshire

Common Python implementations do not support the tail call elimination optimisation, so this will blow the stack. This is trivially demonstrated by using it to write an infinite loop:

>>> def do_while():
...     result = False
...     if result:
...         return True
...     else:
...         return do_while()
...
>>> do_while()
Traceback (most recent call last):
  File "<stdin>", line 6, in do_while
  File "<stdin>", line 6, in do_while
  File "<stdin>", line 6, in do_while
  ...
  File "<stdin>", line 6, in do_while
  File "<stdin>", line 6, in do_while
  File "<stdin>", line 6, in do_while
RuntimeError: maximum recursion depth exceeded

Also, do-while loops continue iterating whilst the predicate is true, but your version continues while it its false. A version which corrects these flaws might look something like:

while True:
     result = do_something()
     if not result:
         break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.