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

其他回答

while condition is True: 
  stuff()
else:
  stuff()

Python 3.8给出了答案。

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

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

快速攻击:

def dowhile(func = None, condition = None):
    if not func or not condition:
        return
    else:
        func()
        while condition():
            func()

像这样使用:

>>> x = 10
>>> def f():
...     global x
...     x = x - 1
>>> def c():
        global x
        return x > 0
>>> dowhile(f, c)
>>> print x
0

我是这样做的……

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

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

while not condition:

etc.

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

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