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

Python (211) 2023-05-24 23:38:31

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

下面简单介绍一下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

THE END

发表回复