Python3 basics-break and continue statements and the else clause in loops

The break statement can jump out of the loop body of for and while. If you terminate from a for or while loop, any corresponding loop else block will not be executed.

The continue statement is used to tell Python to skip the remaining statements in the current loop block, and then continue to the next loop.

The loop statement can have an else clause, which is executed when the exhaustive list (in a for loop) or the condition becomes false (in a while loop) that causes the loop to terminate, but it is not executed when the loop is terminated by a break.

 

Example 1: break

#!/usr/bin/python3
for i in range(10):
    if i == 5:
        print("循环至5,跳出循环",i)
        break
    print("当前数字为:",i)

Results of the:

Example 2: continue

#!/usr/bin/python3
for i in range(10):
    if i == 5:
        print("循环至5,重新开始执行",i)
        continue
    print("当前数字为:",i)

Results of the:

Example 3: Else in a loop statement

#!/usr/bin/python3
for i in range(10):
    if i == 5:
        print("循环至5,跳出循环",i)
        break
    else:
        print("当前数字为:",i)

Example 4: pass statement

Python pass is an empty statement to maintain the integrity of the program structure.

pass does not do anything, generally used as a placeholder statement, the following example

 

#!/usr/bin/python3 
for i in range(10): 
    if i == 5: 
         pass 
         print("Execute pass block") 
    print("The current number is:",i) 
print("bye bye!")

 

Guess you like

Origin blog.csdn.net/jundao1997/article/details/106421945