python循环中的else_python 循环中else的简单示例

导读热词对python这个高级语言感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编两巴掌来看看吧!

众多语言中都有if else这对条件选择组合,但是在python中还有更多else使用的地方,比如说循环for,或者while都可以和else组合。

下面简单介绍一下for-else while-else组合

循环组合中的else执行的情况下是循环正常结束(即不是使用break退出)。如下列代码:

# @param 你所不知道的python 循环中的else

# @author 编程之家 jb51.cc|www.www.jb51.cc

numbers = [1,2,3,4,5]

for n in numbers:

if (n > 5):

print('the value is %d '%(n))

break

else:

print('the for loop does not end with break')

i = 0

while(numbers[i] < 5):

print('the index %d value is %d'%(i,numbers[i]))

if (numbers[i] < 0) :

break

i = i + 1

else:

print('the loop does not end with break')

numbers = [1,5]

for n in numbers:

if (n > 5):

print('the value is %d '%(n))

break

else:

print('the for loop does not end with break')

i = 0

while(numbers[i] < 5):

print('the index %d value is %d'%(i,numbers[i]))

if (numbers[i] < 0) :

break

i = i + 1

else:

print('the loop does not end with break')

# End www.jb51.cc

执行结果如下:

# @param 你所不知道的python 循环中的else

# @author 编程之家 jb51.cc|www.www.jb51.cc

C:\Python27>python.exe for_else.py

the for loop does not end with break

the index 0 value is 1

the index 1 value is 2

the index 2 value is 3

the index 3 value is 4

the loop does not end with break

# End www.jb51.cc

相关文章

总结

如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。

如您喜欢交流学习经验,点击链接加入交流1群:1065694478(已满)交流2群:163560250

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值