for/else 和 while/else 中的 else 语句后的内容,在循环正常结束时,才会执行。换一句话说,当 for 循环或者 While 循环遇到 break 跳出循环时,else 语句后的内容则不执行。这个特性可以让某些行为变得更优雅,比如搜索过程。一般我们可能会利用一个标识变量(flag varable),当条件满足时,改变标识变量的值,然后跳出循环。比如下面这个例子,判断 John 是不是我们的顾客:
customers = ['Tom', 'Mike', 'Jeff', 'Tony']is_John =Falsefor c in customers:if'John'in customers: is_John =Truebreakif is_John:print('John is our customer.')else:print('John is not our customer.')
John is not our customer.
利用 else 语句,则不需要设置标识变量,当循环正常结束时,则表明 John 不是我们的顾客。
customers = ['Tom', 'Mike', 'Jeff', 'Tony']for c in customers:if'John'in customers:print('John is our customer.')breakelse:print('John is not our customer.')