tags:

views:

647

answers:

4

Possible Duplicate:
do-while loop in python?

Is there a

do until x:
    ...

in Python, or a nice way to implement such a looping construct?

+15  A: 

There is no do-while loop in python.

This is a similar construct, taken from the link above.

 while True:
     do_something()
     if condition():
        break
theycallmemorty
BTW, this is called "loop-and-a-half". Python continues to support this construct because it's one of the easiest loop patterns to correctly write and understand. See http://www.cs.duke.edu/~ola/patterns/plopd/loops.html#loop-and-a-half
Brandon Corfman
@Brandon: I didn't know this term, +1 for sharing that.
Adam Byrtek
+4  A: 

There's no prepackaged "do-while", but the general Python way to implement peculiar looping constructs is through generators and other iterators, e.g.:

import itertools

def dowhile(predicate):
  it = itertools.repeat(None)
  for _ in it:
    yield
    if not predicate(): break

so, for example:

i=7; j=3
for _ in dowhile(lambda: i<j):
  print i, j
  i+=1; j-=1

executes one leg, as desired, even though the predicate's already false at the start.

It's normally better to encapsulate more of the looping logic into your generator (or other iterator) -- for example, if you often have cases where one variable increases, one decreases, and you need a do/while loop comparing them, you could code:

def incandec(i, j, delta=1):
  while True:
    yield i, j
    if j <= i: break
    i+=delta; j-=delta

which you can use like:

for i, j in incandec(i=7, j=3):
  print i, j

It's up to you how much loop-related logic you want to put inside your generator (or other iterator) and how much you want to have outside of it (just like for any other use of a function, class, or other mechanism you can use to refactor code out of your main stream of execution), but, generally speaking, I like to see the generator used in a for loop that has little (ideally none) "loop control logic" (code related to updating state variables for the next loop leg and/or making tests about whether you should be looping again or not).

Alex Martelli
A: 

no. use

while 1:
 ...statements...
  if cond:
    break
f0b0s
Why `while 1`? What's wrong with `while True`? Why force a conversion from int to bool?
S.Lott
+1  A: 

I prefer to use a looping variable, as it tends to read a bit nicer than just "while 1:", and no ugly-looking break statement:

finished = False
while not finished:
    ... do something...
    finished = evaluate_end_condition()
Paul McGuire