51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

手机号码,快捷登录

查看: 3322|回复: 1
打印 上一主题 下一主题

[python] python中的else语句

[复制链接]
  • TA的每日心情
    无聊
    10 小时前
  • 签到天数: 493 天

    连续签到: 3 天

    [LV.9]测试副司令

    跳转到指定楼层
    1#
    发表于 2018-12-19 13:16:38 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
    python中的for和while循环支持else分支,else中的代码只有在没有break的情况下运行,如下:
    1. def contains(haystack, needle):
    2.     """
    3.     Throw a ValueError if `needle` not
    4.     in `haystack`.
    5.     """
    6.     for item in haystack:
    7.         if item == needle:
    8.             break
    9.     else:
    10.         # The `else` here is a
    11.         # "completion clause" that runs
    12.         # only if the loop ran to completion
    13.         # without hitting a `break` statement.
    14.         raise ValueError('Needle not found')

    15. >>> contains([23, 'needle', 0xbadc0ffee], 'needle')
    16. None

    17. >>> contains([23, 42, 0xbadc0ffee], 'needle')
    18. ValueError: "Needle not found"
    复制代码
    其实上有时候用raise也能实现相似功能,如下:
    1. def better_contains(haystack, needle):
    2.     for item in haystack:
    3.         if item == needle:
    4.             return
    5.     raise ValueError('Needle not found')
    复制代码
    这样更符合python风格。
    1. if needle not in haystack:
    2.     raise ValueError('Needle not found')
    复制代码


    分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    收藏收藏
    回复

    使用道具 举报

    本版积分规则

    关闭

    站长推荐上一条 /1 下一条

    小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

    GMT+8, 2024-9-20 20:26 , Processed in 0.064281 second(s), 22 queries .

    Powered by Discuz! X3.2

    © 2001-2024 Comsenz Inc.

    快速回复 返回顶部 返回列表