Python循环结构中else用法(入门必读)

Python 中,无论是 while 循环还是 for 循环,其后都可以紧跟着一个 else 代码块,它的作用是,当循环条件为 False 跳出循环时,程序会最先执行 else 代码块中的代码。如下代码示范了为 while 循环定义 else 代码块:count_i = 0while count_i < 5: print('count_i小于5: ', count_i) ...
摘要由CSDN通过智能技术生成

Python 中,无论是 while 循环还是 for 循环,其后都可以紧跟着一个 else 代码块,它的作用是,当循环条件为 False 跳出循环时,程序会最先执行 else 代码块中的代码。

如下代码示范了为 while 循环定义 else 代码块:

count_i = 0
while count_i < 5:
    print('count_i小于5: ', count_i)
    count_i += 1
else:
    print('count_i大于或等于5: ', count_i)

运行上面程序,可以看到如下输出结果:

count_i小于5:  0
count_i小于5:  1
count_i小于5:  2
count_i小于5:  3
count_i小于5:  4
count_i大于或等于5:  5

从上面的运行过程来看,当循环条件 count i < 5 变成 False 时,程序执行了 while 循环的 else 代码块。

简单来说,程序在结束循环之前,会先执行 else 代码块。从这个角度来看,else 代码块其实没有太大的价值,将 else 代码块直接放在循环体之外即可。也就是说,上面代码其实可改为如下形式:

count_i = 0
while count_i < 5:
    print('count_i小于5: ', count_i)
    count_i += 1
print('count_i大于或等于5:
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值