在Python中模拟do-while循环?

萝らか妹 提交于 2020-08-16 12:07:29

问题:

I need to emulate a do-while loop in a Python program. 我需要在Python程序中模拟do-while循环。 Unfortunately, the following straightforward code does not work: 不幸的是,以下简单的代码不起作用:

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"

Instead of "1,2,3,done", it prints the following output: 而不是“1,2,3,完成”,它打印以下输出:

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

What can I do in order to catch the 'stop iteration' exception and break a while loop properly? 我能做些什么来捕获'stop iteration'异常并正确地打破while循环?

An example of why such a thing may be needed is shown below as pseudocode. 以下将伪代码示为可能需要这样的事物的示例。

State machine: 状态机:

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

解决方案:

参考一: https://stackoom.com/question/37KW/在Python中模拟do-while循环
参考二: https://oldbug.net/q/37KW/Emulate-a-do-while-loop-in-Python
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!