Is there a "do … until" in Python?

Question:

Is there a

do until x:
    ...

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

Asked By: Matt Joiner

||

Answers:

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
Answered By: theycallmemorty

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).

Answered By: Alex Martelli

No there isn’t. Instead use a while loop such as:

while 1:
 ...statements...
  if cond:
    break
Answered By: f0b0s

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()
Answered By: PaulMcG
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.