Emulate a do-while loop in Python?

后端 未结 16 871
伪装坚强ぢ
伪装坚强ぢ 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.

提交回复
热议问题