Python's return, break, and continue differences (detailed examples)

Posted by sunnypal on Tue, 31 Dec 2019 13:54:59 +0100

form: https://zhidao.baidu.com/question/1958192745292032580.html

 

Return will return another function directly, and the function is finished. All code in the function body will no longer execute, so the loop in the function body can no longer run.

 

If you need to let the loop continue, you can't return the function. Instead, you should choose break or continue.

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.

 

#coding=gbk
#This is the code module used in the test
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, 5):
        for i in range(0, 5):
            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("break")
    return_continue_break("continue")
    return_continue_break("return") 

Run: return "continue" break ("break")

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:2, 2
executed!
j_i:2, 3
executed!
j_i:2, 4
j_i:3, 0
executed!
j_i:3, 1
executed!
j_i:3, 2
executed!
j_i:3, 3
executed!
j_i:3, 4
j_i:4, 0
executed!
j_i:4, 1
executed!
j_i:4, 2
executed!
j_i:4, 3
executed!
j_i:4, 4

Run: return "continue" break ("continue")

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:2, 2
executed!
j_i:2, 3
executed!
j_i:2, 4
j_i:3, 0
executed!
j_i:3, 1
executed!
j_i:3, 2
executed!
j_i:3, 3
executed!
j_i:3, 4
j_i:4, 0
executed!
j_i:4, 1
executed!
j_i:4, 2
executed!
j_i:4, 3
executed!
j_i:4, 4

Run: return "continue" break ("return")

j_i:0, 0
executed!
j_i:0, 1
executed!
j_i:0, 2
executed!
j_i:0, 3
executed!
j_i:0, 4