Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python loop that always executes at least once? [duplicate]

Tags:

python

loops

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)

like image 385
Trindaz Avatar asked Jun 23 '11 23:06

Trindaz


2 Answers

while True:
    #loop body
    if (!condition): break
like image 136
Petar Ivanov Avatar answered Sep 28 '22 08:09

Petar Ivanov


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

like image 20
Karl Knechtel Avatar answered Sep 28 '22 07:09

Karl Knechtel