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

当前回答

我是这样做的……

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

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

while not condition:

etc.

其他回答

Python 3.8给出了答案。

它叫做赋值表达式。从文档中可以看到:

# Loop over fixed length blocks
while (block := f.read(256)) != '':
    process(block)

用于包含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循环是这样的:

xBool = True
# A counter to force a condition (eg. yCount = some integer value)

while xBool:
    # set up the condition (eg. if yCount > 0):
        (Do something)
        yCount = yCount - 1
    else:
        # (condition is not met, set xBool False)
        xBool = False

我也可以在while循环中包含一个for..循环,如果情况允许的话,for循环通过另一组条件。

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

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 相关问题:打破嵌套循环

你为什么不做呢

for s in l :
    print s
print "done"

?