7

Possible Duplicate:
do-while loop in Python?

How do I write a loop in Python that will always be executed at least once, with the test being performed after the first iteration? (different to the 20 or so python examples of for and while loops I found through google and python docs)

Community
  • 1
  • 1
Trindaz
  • 17,029
  • 21
  • 82
  • 111

2 Answers2

17
while True:
    #loop body
    if (!condition): break
Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95
  • 2
    This is what I was already using, but it didn't seem very elegant. – Trindaz Jun 24 '11 at 01:00
  • 3
    @Trindaz: It could be argued that having Yet Another Looping Syntax makes the *language* less elegant. The syntax above is not overly verbose or hard to understand, so the case for having more syntax is not terribly compelling. Also, there have been discussions by the Python devs about adding do-while, and the conclusion is that there is no nice way to make it fit Python's existing syntax, certainly nothing more elegant than the idiom given in this answer. – John Y Jun 24 '11 at 01:42
  • 1
    If there was a keyword `dowhile` whose use was syntactically identical to `while` but the difference was it'd run the loop first, I'd use it. – Steven Lu Jun 12 '13 at 21:01
1

You could try:

def loop_body():
    # implicitly return None, which is false-ish, at the end


while loop_body() or condition: pass

But realistically I think I would do it the other way. In practice, you don't really need it that often anyway. (Even less often than you think; try to refactor in other ways.)

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153