Emulate a do-while loop in Python?

后端 未结 16 834
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 06:47

I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work:

list_of_ints = [ 1, 2, 3 ]
iterator =         


        
16条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 07:21

    Exception will break the loop, so you might as well handle it outside the loop.

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

    I guess that the problem with your code is that behaviour of break inside except is not defined. Generally break goes only one level up, so e.g. break inside try goes directly to finally (if it exists) an out of the try, but not out of the loop.

    Related PEP: http://www.python.org/dev/peps/pep-3136
    Related question: Breaking out of nested loops

提交回复
热议问题