python中的else语句
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(, 'needle')
None
>>> contains(, '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')
支持分享
页:
[1]