The difference between break, continue, exit() and pass in python

break: jump out of the loop and no longer execute

	-Python break语句,就像在C语言中,打破了最小封闭for或while循环。
	-break语句用来终止循环语句,即循环条件没有False条件或者序列还没被完全递归完,也会停止执行循环语句。
	-break语句用在while和for循环中。
	-如果您使用嵌套循环,break语句将停止执行最深层的循环,并开始执行下一行代码。

Example:

while True:
    print("123")
    break
    print("456")

# break是终止本次循环,比如你很多个for循环,你在其中一个for循环里写了一个break,满足条件,只会终止这个for里面的循环,程序会跳到上一层for循环继续往下走
for i in range(5):
    print("-----%d-----" % i)
    for j in range(6):
        if j > 4:
            break
        print(j)

result:

123
# 这里遇到j>5的时候第二层的for就不循环了,继续跳到上一层循环
-----0-----
0
1
2
3
4
-----1-----
0
1
2
3
4
-----2-----
0
1
2
3
4
-----3-----
0
1
2
3
4
-----4-----
0
1
2
3
4

continue: Jump out of this loop and execute the next one

	-Python continue 语句跳出本次循环,而break跳出整个循环。
	-continue 语句用来告诉Python跳过当前循环的剩余语句,然后继续进行下一轮循环。
	-continue语句用在while和for循环中。

Example:

for letter in 'Python':
    if letter == 'h':
        continue  # 此处跳出for枚举'h'的那一次循环
    print('当前字母 :', letter)

result:

当前字母 : P
当前字母 : y
当前字母 : t
当前字母 : o
当前字母 : n

exit(): End the entire program

Example:

for element in "Python":
    if element == "t":
        exit()
    else:
        print(element)

result:

P
y

pass: do nothing, only play a role as a placeholder

Example:

for element in "Python":
    if element == "y":
        pass
    else:
        print(element)

result:

P
t
h
o
n

Guess you like

Origin blog.csdn.net/plan_jok/article/details/110002529