教程集 www.jiaochengji.com
教程集 >  Python编程  >  Python入门  >  正文 你所不知道的python循环中的else

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

发布时间:2021-05-24   编辑:jiaochengji.com
教程集为您提供你所不知道的python循环中的else等资源,欢迎您收藏本站,我们将为您提供最新的你所不知道的python循环中的else资源

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

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

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

numbers= [1,2,3,4,5]
for nin 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,2,3,4,5]
for nin 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')

执行结果如下:

C:\Python27>python.exe for_else.py
thefor loop doesnot end withbreak
the index0 valueis 1
the index1 valueis 2
the index2 valueis 3
the index3 valueis 4
the loop doesnot end withbreak


您可能感兴趣的文章:
python之流程控制语句
你所不知道的python循环中的else
Python break用法详解
Python(for和while)循环嵌套及用法
Python中for循环语句和while循环语句有何不同
如何重复运行python程序
Python while循环详解
Python中迭代器的实现
python中for循环的底层实现
python学完基础学什么

[关闭]
~ ~