【Python 技巧】“for”(和“while”)循环可以有一个“else”分支

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

【Python 技巧】“for”(和“while”)循环可以有一个“else”分支_第1张图片

你可能感兴趣的:(python)