我需要在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

当前回答

用于包含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

其他回答

看看这是否有帮助:

在异常处理程序中设置一个标志,并在处理s之前检查它。

flagBreak = false;
while True :

    if flagBreak : break

    if s :
        print s
    try :
        s = i.next()
    except StopIteration :
        flagBreak = true

print "done"

异常将打破循环,所以您不妨在循环之外处理它。

try:
  while True:
    if s:
      print s
    s = i.next()
except StopIteration:   
  pass

我猜你的代码的问题是,除了没有定义内部中断的行为。通常break只上一层,例如try内部的break直接进入finally(如果存在的话)一个out of try,而不是out of循环。

相关PEP: http://www.python.org/dev/peps/pep-3136 相关问题:打破嵌套循环

我是这样做的……

condition = True
while condition:
     do_stuff()
     condition = (<something that evaluates to True or False>)

对我来说,这似乎是一个简单的解决方案,我很惊讶我还没有在这里看到它。这显然也可以被颠倒

while not condition:

etc.

我相信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