Create a gist now

Instantly share code, notes, and snippets.

Embed
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

This comment has been minimized.

Show comment
Hide comment
@rob-smallshire

rob-smallshire Apr 22, 2013

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

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