title: How to emulate a do-while loop?
body: <p>I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work:</p>
  
  <pre><code>list_of_ints = [ 1, 2, 3 ]
  iterator = list_of_ints.__iter__()
  element = None
  
  while True:
    if element:
      print element
  
    try:
      element = iterator.next()
    except StopIteration:
      break
  
  print "done"
  </code></pre>
  
  <p>Instead of "1,2,3,done", it prints the following output:</p>
  
  <pre><code>[stdout:]1
  [stdout:]2
  [stdout:]3
  None['Traceback (most recent call last):
  ', '  File "test_python.py", line 8, in &lt;module&gt;
      s = i.next()
  ', 'StopIteration
  ']
  </code></pre>
  
  <p>What can I do in order to catch the 'stop iteration' exception and break a while
  loop properly?</p>
  
  <p>An example of why such a thing may be needed is shown below as pseudocode.</p>
  
  <p>State machine:</p>
  
  <pre><code>s = ""
  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] )
      else
        state = STATE_CODE
        # Re-evaluate same line
        continue
    try :
      s = i.next()
    except StopIteration :
      break
  </code></pre>