您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python 循环中else的简单示例

5b51 2022/1/14 8:14:48 python 字数 1905 阅读 286 来源 www.jb51.cc/python

python 循环中else的简单示例

概述

众多语言中都有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

总结

以上是编程之家为你收集整理的python 循环中else的简单示例全部内容,希望文章能够帮你解决python 循环中else的简单示例所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶