995

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

我该怎么做才能捕获“停止迭代”异常并正确中断 while 循环?

下面以伪代码的形式显示了为什么需要这样的东西的示例。

状态机:

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
4

19 回答 19

1226

我不确定您要做什么。你可以像这样实现一个 do-while 循环:

while True:
  stuff()
  if fail_condition:
    break

或者:

stuff()
while not fail_condition:
  stuff()

你在做什么尝试使用 do while 循环来打印列表中的内容?为什么不直接使用:

for i in l:
  print i
print "done"

更新:

那么你有一个行列表吗?你想继续迭代它吗?怎么样:

for s in l: 
  while True: 
    stuff() 
    # use a "break" instead of s = i.next()

这看起来像你想要的吗?使用您的代码示例,它将是:

for s in some_list:
  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] )
        break # get next s
      else:
        state = STATE_CODE
        # re-evaluate same line
        # continues automatically
于 2009-04-13T06:28:43.760 回答
365

这是模拟 do-while 循环的一种非常简单的方法:

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

do-while 循环的关键特性是循环体总是至少执行一次,并且条件在循环体的底部进行评估。此处显示的控制结构无需异常或中断语句即可完成这两项工作。它确实引入了一个额外的布尔变量。

于 2010-03-14T00:09:54.823 回答
91

我下面的代码可能是一个有用的实现,突出了我所理解的之间的主要区别。

因此,在这种情况下,您总是至少经历一次循环。

first_pass = True
while first_pass or condition:
    first_pass = False
    do_stuff()
于 2014-11-23T23:37:17.577 回答
37
do {
  stuff()
} while (condition())

->

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

你可以做一个功能:

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

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

于 2009-04-13T13:57:02.997 回答
34

异常会打破循环,所以你不妨在循环外处理它。

try:
  while True:
    if s:
      print s
    s = i.next()
except StopIteration:   
  pass

我猜你的代码的问题是没有定义breakinside的行为。except通常break只向上一级,因此例如breakinsidetry直接进入finally(如果存在)一个 out of the try,但不是 out of the loop。

相关 PEP:http
://www.python.org/dev/peps/pep-3136 相关问题:打破嵌套循环

于 2009-04-13T07:06:40.800 回答
17

这是一个不同模式的更疯狂的解决方案——使用协程。代码仍然非常相似,但有一个重要区别;根本没有退出条件!当您停止向其提供数据时,协程(实际上是协程链)就会停止。

def coroutine(func):
    """Coroutine decorator

    Coroutines must be started, advanced to their first "yield" point,
    and this decorator does this automatically.
    """
    def startcr(*ar, **kw):
        cr = func(*ar, **kw)
        cr.next()
        return cr
    return startcr

@coroutine
def collector(storage):
    """Act as "sink" and collect all sent in @storage"""
    while True:
        storage.append((yield))

@coroutine      
def state_machine(sink):
    """ .send() new parts to be tokenized by the state machine,
    tokens are passed on to @sink
    """ 
    s = ""
    state = STATE_CODE
    while True: 
        if state is STATE_CODE :
            if "//" in s :
                sink.send((TOKEN_COMMENT, s.split( "//" )[1] ))
                state = STATE_COMMENT
            else :
                sink.send(( TOKEN_CODE, s ))
        if state is STATE_COMMENT :
            if "//" in s :
                sink.send(( TOKEN_COMMENT, s.split( "//" )[1] ))
            else
                state = STATE_CODE
                # re-evaluate same line
                continue
        s = (yield)

tokens = []
sm = state_machine(collector(tokens))
for piece in i:
    sm.send(piece)

上面的代码将所有标记收集为元组,我假设原始代码之间tokens没有区别。.append().add()

于 2009-11-02T17:32:02.063 回答
17

我这样做的方式如下...

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

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

while not condition:

等等

于 2018-06-23T20:00:26.973 回答
13

Python 3.8 给出了答案。

它被称为赋值表达式。从文档

# Loop over fixed length blocks
while (block := f.read(256)) != '':
    process(block)
于 2020-09-08T08:10:00.420 回答
10

for 包含 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
于 2011-05-10T22:03:06.030 回答
8

我相信这种在 python 上的 do-while 模拟具有最接近 C 和 Java 中存在的 do-while 结构格式的语法格式。

do = True
while do:
    [...]
    do = <condition>
于 2021-05-02T19:17:59.627 回答
7
while condition is True: 
  stuff()
else:
  stuff()
于 2010-11-30T01:38:03.477 回答
7

快速破解:

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
于 2013-04-21T21:42:57.920 回答
4

你为什么不做

for s in l :
    print s
print "done"

?

于 2009-04-13T06:23:44.537 回答
1

看看这是否有帮助:

在异常处理程序中设置一个标志并在处理 s 之前检查它。

flagBreak = false;
while True :

    if flagBreak : break

    if s :
        print s
    try :
        s = i.next()
    except StopIteration :
        flagBreak = true

print "done"
于 2009-04-13T08:17:55.697 回答
1

如果您处于循环时资源不可用或类似的引发异常的情况,您可以使用类似的东西

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
于 2018-05-06T06:01:43.663 回答
1

对我来说,一个典型的 while 循环将是这样的:

xBool = True
# A counter to force a condition (eg. yCount = some integer value)

while xBool:
    # set up the condition (eg. if yCount > 0):
        (Do something)
        yCount = yCount - 1
    else:
        # (condition is not met, set xBool False)
        xBool = False

如果情况允许,我也可以在 while 循环中包含一个for..loop,用于循环另一组条件。

于 2020-03-08T10:08:22.363 回答
1

你想知道:

我该怎么做才能捕获“停止迭代”异常并正确中断 while 循环?

您可以如下所示执行此操作,这还利用了 Python 3.8 中引入的赋值表达式功能(又名“海象运算符”):

list_of_ints = [1, 2, 3]
iterator = iter(list_of_ints)

try:
    while (element := next(iterator)):
        print(element)
except StopIteration:
    print("done")

另一种可能性(适用于 Python 2.6 到 3.x)是为default内置next()函数提供一个参数以避免StopIteration异常:

SENTINEL = object()  # Unique object.
list_of_ints = [1, 2, 3]
iterator = iter(list_of_ints)

while True:
    element = next(iterator, SENTINEL)
    if element is SENTINEL:
        break
    print(element)

print("done")
于 2021-03-13T18:36:04.887 回答
0

内置的iter函数专门执行以下操作:

for x in iter(YOUR_FN, TERM_VAL):
    ...

例如(在 Py2 和 3 中测试):

class Easy:
  X = 0
  @classmethod
  def com(cls):
    cls.X += 1
    return cls.X

for x in iter(Easy.com, 10):
  print(">>>", x)

如果你想给出一个终止条件而不是一个值,你总是可以设置一个等式,并要求该等式为True

于 2020-06-28T19:00:48.870 回答
0

While循环:

while condition:
  logic

做while循环:

while True:
  logic
  if not condition:
    break
于 2022-03-03T17:51:03.800 回答