Python中的 for else

Python中的for循环是有else的可选用法的。

for后面加了else后,for循环结束后(没有break)会进入else执行语句;如果碰到break则会跳过else分支。

示例:

In [1]: fruits = ['apple', 'banana', 'mango']
...: for fruit in fruits:
...: print(fruit.capitalize())
...: else:
...: print('watermelon')
...:
Apple
Banana
Mango
watermelon
In [2]: for n in range(2, 10):
...: for x in range(2, n):
...: if n % x == 0:
...: print( n, 'equals', x, '*', n//x)
...: break
...: else:
...: # loop fell through without finding a factor
...: print(n, 'is a prime number')
...:
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

for else在工程实践中利用得好可以写出更简洁的代码。但,这个语句有挺大的争议,它不简单明了,容易让人困惑和费解,并不Pythonic。很多人也是反对使用for else和while else的。也是《Effective Python: 59 Specific Ways to Write Better Python》中所不提倡的做法。