loops – Is there a do … until in Python?

loops – Is there a do … until in Python?

There is no do-while loop in Python.

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

 while True:
     if condition():

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

loops – Is there a do … until in Python?

Theres 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:
    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 predicates already false at the start.

Its 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

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

Leave a Reply

Your email address will not be published. Required fields are marked *