我需要在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 True:
    try:
        # stuff
        stuff_1()
        if some_cond:
            continue
        if other_cond:
            break
        stuff_2()
    finally:
        # condition
        if not condition:
            break

[x]条件只检查后运行的东西 [x]不是函数调用 [x]条件不是函数调用 [x]的东西可以包含流量控制 []避免检查条件,如果东西叫break(可以用另一个布尔值)

其他回答

我是这样做的……

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

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

while not condition:

etc.

用于包含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
do {
  stuff()
} while (condition())

->

while True:
  stuff()
  if not condition():
    break

你可以做一个函数:

def do_while(stuff, condition):
  while condition(stuff()):
    pass

但 1)它很丑。 2) Condition应该是一个只有一个参数的函数,应该由东西填充(这是不使用经典while循环的唯一原因)。

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上的这个do-while模拟的语法格式与C和Java中呈现的do-while结构格式最接近。

do = True
while do:
    [...]
    do = <condition>