在循环中使用else语句

Python
Author

Tom

Published

January 15, 2023

for/elsewhile/else 中的 else 语句后的内容,在循环正常结束时,才会执行。换一句话说,当 for 循环或者 While 循环遇到 break 跳出循环时,else 语句后的内容则不执行。这个特性可以让某些行为变得更优雅,比如搜索过程。一般我们可能会利用一个标识变量(flag varable),当条件满足时,改变标识变量的值,然后跳出循环。比如下面这个例子,判断 John 是不是我们的顾客:

customers = ['Tom', 'Mike', 'Jeff', 'Tony']
is_John = False
for c in customers:
    if 'John' in customers:
        is_John = True
        break
    
if 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.')
        break
else:
    print('John is not our customer.')
John is not our customer.

利用 else 语句也可以执行一些必要内容。比如使用 selenium 爬虫结束后,我们需要 driver.close()driver.quit() 释放内存资源。那么在循环解析页面时,我们也可以把这两个语句放到 else 后面。

# pseudocode
for url in url_list:
    driver.get(url)
else:
    driver.close()
    driver.quit()