相关疑难解决方法(0)

在Python中模拟do-while循环?

我需要在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"
Run Code Online (Sandbox Code Playgroud)

而不是"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
']
Run Code Online (Sandbox Code Playgroud)

我能做些什么来捕获'stop iteration'异常并正确地打破while循环?

以下将伪代码示为可能需要这样的事物的示例.

状态机:

s = ""
while True :
  if state is STATE_CODE :
    if "//" in s :
      tokens.add( TOKEN_COMMENT, s.split( "//" )[1] )
      state = …
Run Code Online (Sandbox Code Playgroud)

python while-loop do-while

731
推荐指数
13
解决办法
120万
查看次数

标签 统计

do-while ×1

python ×1

while-loop ×1