Python的‘for’和‘while’循环支持‘else’分句,分句仅在循环体没有触发‘break’语句并终止时执行。
1# Python's `for` and `while` loops 2# support an `else` clause that executes 3# only if the loops terminates without 4# hitting a `break` statement. 5 6def contains(haystack, needle): 7 """ 8 Throw a ValueError if `needle` not 9 in `haystack`. 10 """ 11 for item in haystack: 12 if item == needle: 13 break 14 else: 15 # The `else` here is a 16 # "completion clause" that runs 17 # only if the loop ran to completion 18 # without hitting a `break` statement. 19 raise ValueError('Needle not found') 20 21 22>>> contains([23, 'needle', 0xbadc0ffee], 'needle') 23None 24 25>>> contains([23, 42, 0xbadc0ffee], 'needle') 26ValueError: "Needle not found" 27 28 29# Personally, I'm not a fan of the `else` 30# "completion clause" in loops because 31# I find it confusing. I'd rather do 32# something like this: 33def better_contains(haystack, needle): 34 for item in haystack: 35 if item == needle: 36 return 37 raise ValueError('Needle not found') 38 39# Note: Typically you'd write something 40# like this to do a membership test, 41# which is much more Pythonic: 42if needle not in haystack: 43 raise ValueError('Needle not found')
就个人而言,我不热衷于在循环体中使用条件完成分句,因为这太令人困惑了。我倾向于在整个函数中直接返回或者抛出错误。
注意:通常这种语法在测试成员身份时使用,这看