How to emulate a do-while loop? How to emulate a do-while loop? python python

How to emulate a do-while loop?

I am not sure what you are trying to do. You can implement a do-while loop like this:

while True:  stuff()  if fail_condition:    break


stuff()while not fail_condition:  stuff()

What are you doing trying to use a do while loop to print the stuff in the list? Why not just use:

for i in l:  print iprint "done"


So do you have a list of lines? And you want to keep iterating through it? How about:

for s in l:   while True:     stuff()     # use a "break" instead of s =

Does that seem like something close to what you would want? With your code example, it would be:

for s in some_list:  while True:    if state is STATE_CODE:      if "//" in s:        tokens.add( TOKEN_COMMENT, s.split( "//" )[1] )        state = STATE_COMMENT      else :        tokens.add( TOKEN_CODE, s )    if state is STATE_COMMENT:      if "//" in s:        tokens.append( TOKEN_COMMENT, s.split( "//" )[1] )        break # get next s      else:        state = STATE_CODE        # re-evaluate same line        # continues automatically

Here's a very simple way to emulate a do-while loop:

condition = Truewhile condition:    # loop body here    condition = test_loop_condition()# end of loop

The key features of a do-while loop are that the loop body always executes at least once, and that the condition is evaluated at the bottom of the loop body. The control structure show here accomplishes both of these with no need for exceptions or break statements. It does introduce one extra Boolean variable.

My code below might be a useful implementation, highlighting the main difference between vs as I understand it.

So in this one case, you always go through the loop at least once.

first_pass = Truewhile first_pass or condition:    first_pass = False    do_stuff()