Emulate a do-while loop in Python?

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

    Here's a very simple way to emulate a do-while loop:

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

    The key features of a do-while loop are that the loop body always executes at least once, and that the condition is evaluated at the bottom of the loop body. The control structure show here accomplishes both of these with no need for exceptions or break statements. It does introduce one extra Boolean variable.

    0 讨论(0)
  • 2020-11-22 07:40

    Quick hack:

    def dowhile(func = None, condition = None):
        if not func or not condition:
            return
        else:
            func()
            while condition():
                func()
    

    Use like so:

    >>> x = 10
    >>> def f():
    ...     global x
    ...     x = x - 1
    >>> def c():
            global x
            return x > 0
    >>> dowhile(f, c)
    >>> print x
    0
    
    0 讨论(0)
  • 2020-11-22 07:41

    for a do - while loop containing try statements

    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()
    

    alternatively, when there's no need for the 'finally' clause

    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
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题