Skip to content

Instantly share code, notes, and snippets.

@metaperl
Created April 22, 2013 08:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save metaperl/5433377 to your computer and use it in GitHub Desktop.
Save metaperl/5433377 to your computer and use it in GitHub Desktop.
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
Copy link

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