我需要在Python程序中模拟一个do-while循环。不幸的是,下面的简单代码不能工作:

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"

不是"1,2,3,done",而是输出如下:

[stdout:]1
[stdout:]2
[stdout:]3
None['Traceback (most recent call last):
', '  File "test_python.py", line 8, in <module>
    s = i.next()
', 'StopIteration
']

为了捕获“停止迭代”异常并中断一段时间,我能做些什么 循环正常吗?

下面的伪代码显示了为什么需要这样一个东西的示例。

状态机:

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

当前回答

我不知道你想干什么。你可以像这样实现一个do-while循环:

while True:
  stuff()
  if fail_condition:
    break

Or:

stuff()
while not fail_condition:
  stuff()

你为什么要用一个do while循环来打印列表中的东西?为什么不直接使用:

for i in l:
  print i
print "done"

更新:

你有台词清单吗?你想一直遍历它吗?如何:

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

这看起来像是你想要的吗?对于您的代码示例,它将是:

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

其他回答

用于包含try语句的do - while循环

loop = True
while loop:
    generic_stuff()
    try:
        questionable_stuff()
#       to break from successful completion
#       loop = False  
    except:
        optional_stuff()
#       to break from unsuccessful completion - 
#       the case referenced in the OP's question
        loop = False
   finally:
        more_generic_stuff()

或者,当不需要'finally'从句时

while True:
    generic_stuff()
    try:
        questionable_stuff()
#       to break from successful completion
#       break  
    except:
        optional_stuff()
#       to break from unsuccessful completion - 
#       the case referenced in the OP's question
        break
while condition is True: 
  stuff()
else:
  stuff()

内置的iter函数具体做到了这一点:

for x in iter(YOUR_FN, TERM_VAL):
    ...

例如(在Py2和3中测试过):

class Easy:
  X = 0
  @classmethod
  def com(cls):
    cls.X += 1
    return cls.X

for x in iter(Easy.com, 10):
  print(">>>", x)

如果你想给出一个终止条件而不是一个值,你总是可以设置一个等式,并要求这个等式为True。

我相信python上的这个do-while模拟的语法格式与C和Java中呈现的do-while结构格式最接近。

do = True
while do:
    [...]
    do = <condition>

如果您正在循环而资源不可用或抛出异常的类似情况下,您可以使用类似于

import time

while True:
    try:
       f = open('some/path', 'r')
    except IOError:
       print('File could not be read. Retrying in 5 seconds')   
       time.sleep(5)
    else:
       break