原文链接: Python for-else 语句
当循环正常退出时,包括循环结束和continue时,才会调用else中的语句
当使用break结束循环时,不会执行else中的语句
for i in range(5):
print(i)
else:
print('else')
0
1
2
3
4
else
for i in range(5):
print(i)
if i == 3:
break
else:
print('else')
0
1
2
3
for i in range(5):
print(i)
if i == 3:
continue
else:
print('else')
0
1
2
3
4
else
一种使用场景,当没有找到需要处理的items时,会执行not_found
for item in container:
if search_something(item):
# Found it!
process(item)
break
else:
# Didn't find anything..
not_found_in_container()
素数的寻找,内循环中,如果没有执行break,则表示没有不是2--n-1的因子,也就是说该数是素数
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.0
5 is a prime number
6 equals 2 * 3.0
7 is a prime number
8 equals 2 * 4.0
9 equals 3 * 3.0