知行编程网知行编程网  2023-01-04 11:30 知行编程网 隐藏边栏  2 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于python循环结构中的else怎么使用的相关知识,希望可以帮到处于编程学习途中的小伙伴

如何在python循环结构中使用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

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享