return/break/continue usage in Python

break: jump out of the current loop and continue to execute the outer code.

Continue: jump out of this loop, continue to run the loop from the next iteration, the inner loop is completed, and the outer code continues to run.

return: directly returns a function. All code in the function body (including the loop body) will not be executed.

Use the following example code to explain:

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

 

Posted on Sat, 02 Nov 2019 15:02:07 -0700 by Cultureshock