Python_for循环
1.语法
for 临时变量 in 序列:
重复执行的代码
········
#for语法练习
str='hello'
for i in str:
print(i,end='\t')
2.break
break:终止此次循环
# break练习
# 需求:打印到e停止
str='hello'
for i in str:
if i=='e':
break
print(i, end='\t')
3.continue
continue:退出当前一次循环,继续执行下一次循环
# continue练习
# 需求:不打印e,其余正常打印
str='hello'
for i in str:
if i=='e':
continue
print(i, end='\t')
4.while·····else
(1)注意:循环可以和else配合使用,else下方缩进的代码指的是当循环正常结束之后要执行的代码
(2)语法:
while 条件:
条件成立重复执行的代码
else:
循环正常结束之后要执行的代码
# while·····else
# 需求:输出5遍hello,输出1遍world
i=0
while i<5:
print('hello')
i+=1
# print('world')
else:
print('world')
5.while····else之break
注意:break终止循环的情况下,else下方缩进的代码将不执行
# while····else之break
# 需求:第3遍的时候终止
i=0
while i<5:
if i==3:
break
print('hello')
i+=1
else:
print('world')
6.while····else之continue
注意:在continue控制下是可以正常结束的,当循环结束后,还会执行else缩进代码
# while····else之continue
# 需求:第3遍不输出,其余正常输出
i=0
while i<5:
if i==3:
i+=1 #计数器必须写在continue之前
continue
print('hello')
i+=1
else:
print('world')
7.for····else语法
for 临时变量 in 系列:
重复执行的代码
·····
else:
循环正常结束之后要执行的代码
注意:else下方缩进的代码指的是当循环正常结束之后要执行的代码
# for····else语法
str='hello'
for i in str:
print(i,end='\t')
else:
print('world')
7.for····else之break
注意:break终止循环的情况下,else下方缩进的代码将不执行
# for····else语法之break
# 需求:打印到e停止
str='hello'
for i in str:
if i=='e':
break
print(i,end='\t')
else:
print('world')
8.for····else之continue
在continue控制下是可以正常结束的,当循环结束后,还会执行else缩进代码
# for····else语法之continue
# 需求:不打印e,其余正常打印
str='hello'
for i in str:
if i=='e':
continue
print(i,end='\t')
else:
print('world')