Emulate a do-while loop in Python?

后端 未结 16 1057
伪装坚强ぢ
伪装坚强ぢ 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:43

    The built-in iter function does specifically that:

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

    E.g. (tested in Py2 and 3):

    class Easy:
      X = 0
      @classmethod
      def com(cls):
        cls.X += 1
        return cls.X
    
    for x in iter(Easy.com, 10):
      print(">>>", x)
    

    If you want to give a condition to terminate instead of a value, you always can set an equality, and require that equality to be True.

提交回复
热议问题