Python_for循环

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')

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值