# Python 的`for` 和`while` 循环支持`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"
# 就我个人而言,我不喜欢循环中的`else`“完成子句”,因为我觉得它令人困惑。
# 我宁愿做这样的事情:
def better_contains(haystack, needle):
for item in haystack:
if item == needle:
return
raise ValueError('Needle not found')
# 注意:通常你会写这样的东西来做一个会员测试,这更像 Pythonic:
if needle not in haystack:
raise ValueError('Needle not found')

**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。