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

当前回答

While循环:

while condition:
  print("hello")
  

执行while循环:

while True:
  print("hello")
  if not condition:
    break

你也可以使用任何真布尔值作为条件:

while 1:
  print("hello")
  if not condition:
    break

另一个变体:

check = 1
while check:
    print("hello")
    check = condition

其他回答

Python 3.8给出了答案。

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

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

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

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

你为什么不做呢

for s in l :
    print s
print "done"

?

While循环:

while condition:
  print("hello")
  

执行while循环:

while True:
  print("hello")
  if not condition:
    break

你也可以使用任何真布尔值作为条件:

while 1:
  print("hello")
  if not condition:
    break

另一个变体:

check = 1
while check:
    print("hello")
    check = condition

下面是一个非常简单的模拟do-while循环的方法:

condition = True
while condition:
    # loop body here
    condition = test_loop_condition()
# end of loop

do-while循环的关键特征是循环体总是至少执行一次,并且条件在循环体的底部计算。这里显示的控制结构实现了这两种功能,不需要异常或break语句。它确实引入了一个额外的布尔变量。