例如python官方文档里举得这个例子
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35直接这样写不是也能实现同样的功能吗?
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
如果一个循环里面有多个地方需要break的话,用while..else..就不用在每个break后面写同样的代码。(记错了)
举个具体的例子,在C时代,可以这么写:
for (i = 0; i < 10; i++)
if (some condition)
break;
if i == 10:
printf("no break\n");
但是在python里面用 for x in xx 的话就不行了,如果没有这样的else的话,就得设置一个额外的flag:
1
2
3
4
5
6
7flag = False
for x in xx:
if some condition:
flag = True
break
if flag:
print 'no break'
看起来很丑;而有了else。
1
2
3
4
5for x in xx:
if some condition:
break
else:
print 'no break'
当前的for被break掉以后,其对应的else不会执行