手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Python 循环中的else

[日期:2013-07-06] 来源:Linux社区  作者:Linux [字体:大 中 小]

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

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

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

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')

执行结果如下:

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

推荐阅读:

Python UNIX和Linux系统管理指南 PDF高清版 http://www.linuxidc.com/Linux/2013-06/86448.htm

Python 用socket模块实现检测端口和检测web服务  http://www.linuxidc.com/Linux/2013-06/86449.htm

linux
相关资讯       python 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款