>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else: # 此处else与for循环对应
... # 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
注:循环语句可能带有一个 else
子句;它会在循环遍历完列表 (使用 for
) 或是在条件变为假 (使用 while
) 的时候被执行,但是不会在循环被 break
语句终止时被执行。