Return/break/continue usage in Python

break: Jump out of the current entire loop, and continue execution to the outer code.

continue: Jump out of this loop and continue to run the loop from the next iteration. After the inner loop is executed, the outer code continues to run.

return: return to the function directly, and all the code in the function body (including the loop body) will not be executed again.

Explain with the following sample code:


def return_continue_break(type):
    if(not type in ["return", "continue", "break"]):
        print '"type" should be "return, continue, break".'
        return
    for j in range(0, 10):
        for i in range(0, 10):
            print "j_i: %d_%d" %(j, i)
            if(i > 3):
               if(type == "return"):
                   return
               elif(type == "continue"):
                   continue
               else:
                   break
            print "executed!"
 
if __name__ == '__main__':
    return_continue_break("return")
    return_continue_break("break")
    return_continue_break("continue")

The output of return is:

j_i: 0_0
executed!
j_i: 0_1
executed!
j_i: 0_2
executed!
j_i: 0_3
executed!
j_i: 0_4

The output of break is:

j_i: 0_0
executed!
j_i: 0_1
executed!
j_i: 0_2
executed!
j_i: 0_3
executed!
j_i: 0_4
j_i: 1_0
executed!
j_i: 1_1
executed!
j_i: 1_2
executed!
j_i: 1_3
executed!
j_i: 1_4
j_i: 2_0
executed!
j_i: 2_1
executed!
.
.
.
j_i: 8_2
executed!
j_i: 8_3
executed!
j_i: 8_4
j_i: 9_0
executed!
j_i: 9_1
executed!
j_i: 9_2
executed!
j_i: 9_3
executed!
j_i: 9_4

The output of continue is:

j_i: 0_0
executed!
j_i: 0_1
executed!
j_i: 0_2
executed!
j_i: 0_3
executed!
j_i: 0_4
j_i: 0_5
j_i: 0_6
j_i: 0_7
j_i: 0_8
j_i: 0_9
j_i: 1_0
executed!
j_i: 1_1
executed!
j_i: 1_2
executed!
j_i: 1_3
executed!
j_i: 1_4
j_i: 1_5
j_i: 1_6
j_i: 1_7
j_i: 1_8
j_i: 1_9
j_i: 2_0
executed!
.
.
.
j_i: 9_0
executed!
j_i: 9_1
executed!
j_i: 9_2
executed!
j_i: 9_3
executed!
j_i: 9_4
j_i: 9_5
j_i: 9_6
j_i: 9_7
j_i: 9_8
j_i: 9_9

 

Guess you like

Origin blog.csdn.net/weixin_41611054/article/details/90675998