5

While python doesn't explicitly allow do-while loops, there are at least 3 reasonable ways to implement them:

1)

while True:
    #loop body
    if not expr():
        break

2)

x = True
while x:
    #loop body
    x = expr()

3)

def f():
    #loop body

f()
while expr():
    f()

Not to mention other methods mentioned here (e.g. coroutines, try-except clauses, iterators, etc), that I assume are non-pythonic under most conditions. I even see some answers arguing that do-while loops are non-pythonic, but I don't know a generic alternative.

Which method is most pythonic? They all have their oddity: 1) begins with an infinite loop, 2) creates a opaque variable at first, and 3) defines a new function. Does anyone have a better method?

Community
  • 1
  • 1
ChrisM
  • 572
  • 7
  • 7
  • 1
    this will get closed since its subjective ... but 2 is the most pythonic imho – Joran Beasley Nov 13 '12 at 18:21
  • 1
    I think this really depends a lot on how `expr` is actually implemented and what you want out of it. – mgilson Nov 13 '12 at 18:27
  • 3
    Slight tangent: there was long discussion on python-list recently about a proposed [new syntax](http://mail.python.org/pipermail/python-list/2012-October/633761.html) to replace all of these. It seems unlikely to go anywhere, though. – Zero Piraeus Nov 13 '12 at 18:31
  • higher-order `dowhile` function? – Marcin Nov 13 '12 at 18:50
  • There are two responses to the "while expression" (which is actually a statement… but never mind that) post that @ZeroPiraeus linked that directly say that #1 is the idiomatic way, and explain why… – abarnert Nov 13 '12 at 20:32

0 Answers0