public
Created

Python lacks a do-while. Here is my preferred solution

  • Download Gist
python-do-while.md
Markdown

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?

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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.