TA的每日心情 | 擦汗 4 小时前 |
---|
签到天数: 526 天 连续签到: 3 天 [LV.9]测试副司令
|
python中的for和while循环支持else分支,else中的代码只有在没有break的情况下运行,如下:
- def contains(haystack, needle):
- """
- Throw a ValueError if `needle` not
- in `haystack`.
- """
- for item in haystack:
- if item == needle:
- break
- else:
- # The `else` here is a
- # "completion clause" that runs
- # only if the loop ran to completion
- # without hitting a `break` statement.
- raise ValueError('Needle not found')
- >>> contains([23, 'needle', 0xbadc0ffee], 'needle')
- None
- >>> contains([23, 42, 0xbadc0ffee], 'needle')
- ValueError: "Needle not found"
复制代码 其实上有时候用raise也能实现相似功能,如下:
- def better_contains(haystack, needle):
- for item in haystack:
- if item == needle:
- return
- raise ValueError('Needle not found')
复制代码 这样更符合python风格。
- if needle not in haystack:
- raise ValueError('Needle not found')
复制代码
|
|