break,continue与pass语句

一,break用法
break 用于跳出当前循环
1,for a in ‘python’:
if a == t:
break
print(‘当前字母:’,a)

执行语句得到 当前字母:p
当前字母:y
2,b=5
while b > 0:
print(‘当前值:’,b)
b=b - 1
if b == 2:
break
print(‘OK’)

执行该语句得到 当前值:5
当前值:4
当前值:3
OK
二,continue用法
continue跳出当前循环的剩余语句,进行下一轮循环
1,for a in ‘python’:
if a == t:
continue
print(‘当前字母:’,a)

执行语句得到 当前字母:p
当前字母:y
当前字母:h
当前字母:0
当前字母:n
2,b=5
while b > 0:
print(‘当前值:’,b)
b=b - 1
if b == 2:
break
print(‘OK’)

执行该语句得到 当前值:5
当前值:4
当前值:3
当前值:1
OK
三,pass语句
pass为空语句,为了保持python结构的完整性,起到占位作用,不做任何事情
for x in apple:
if x == p:
pass
print(‘执行pass块’)
print(‘当前字母:’,x)

执行该语句将得到:当前字母:a
执行pass块
执行pass块
当前字母:p
当前字母:l
注:循环中的else子句,当for循环条件穷尽或while循环条件不成立时执行,但循环被break打断时不执行
查询质数的语句
for a in range(2,10):
for b in range(2,a):
if a % b == 0:
print(a,‘等于’, b ‘
’ a//b)
break
else:
print(a,‘是质数’)*
执行该语句将得到: 2 是质数
3 是质数
4 等于 2 * 2
5 是质数
6 等于 2 * 3
7 是质数
8 等于 2 * 4
9 等于 3 * 3

猜你喜欢

转载自blog.csdn.net/onroadliuyaqiong/article/details/83619282