当前位置: 首页 > 图灵资讯 > 行业资讯> 你所不知道的python循环中的else

你所不知道的python循环中的else

发布时间:2025-09-22 10:55:49

if在许多语言中都有 else是条件选择组合,但python中使用else的地方更多,如循环for或while。

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

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

numbers=[1,2,3,4,5]
forninnumbers:
if(n>5):
print('thevalueis%d'%(n))
break
else:
print('theforloopdoesnotendwithbreak')

i=0
while(numbers[i]<5):
print('theindex%dvalueis%d'%(i,numbers[i]))
if(numbers[i]<0):
break
i=i+1
else:
print('theloopdoesnotendwithbreak')

numbers=[1,2,3,4,5]
forninnumbers:
if(n>5):
print('thevalueis%d'%(n))
break
else:
print('theforloopdoesnotendwithbreak')

i=0
while(numbers[i]<5):
print('theindex%dvalueis%d'%(i,numbers[i]))
if(numbers[i]<0):
break
i=i+1
else:
print('theloopdoesnotendwithbreak')

结果如下:

C:\Python27>python.exefor_else.py
theforloopdoesnotendwithbreak
theindex0valueis1
theindex1valueis2
theindex2valueis3
theindex3valueis4
theloopdoesnotendwithbreak

相关文章

Python中reduce函数和lambda表达式的学习

Python中reduce函数和lambda表达式的学习

2025-09-25
Python小白必学的面向对象

Python小白必学的面向对象

2025-09-25
一个例子解释python装饰器

一个例子解释python装饰器

2025-09-25
深入理解Python的set和dict

深入理解Python的set和dict

2025-09-25
Python中正则表达式的巧妙使用

Python中正则表达式的巧妙使用

2025-09-25
5分钟搞定Python中函数的参数

5分钟搞定Python中函数的参数

2025-09-25