​break​​​ 语句和 C 中的类似,用于跳出最近的 ​​for​​​ 或 ​​while​​ 循环。

循环语句支持 ​​else​​​ 子句;​​for​​​ 循环中,可迭代对象中的元素全部循环完毕,或 ​​while​​​ 循环的条件为假时,执行该子句;​​break​​ 语句终止循环时,不执行该子句。 请看下面这个查找素数的循环示例:

>>> 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

(没错,这段代码就是这么写。仔细看:​​else​​​ 子句属于 ​​for​​ 循环,不属于 ​​if​​​ 语句。)与 ​​if​​​ 语句相比,循环的 ​​else​​​ 子句更像 ​​try​​​ 的 ​​else​​​ 子句: ​​try​​​ 的 ​​else​​​ 子句在未触发异常时执行,循环的 ​​else​​​ 子句则在未运行 ​​break​​​ 时执行。​​try​​​ 语句和异常详见 ​异常的处理。​​continue​​ 语句也借鉴自 C 语言,表示继续执行循环的下一次迭代:

>>> for num in range(2, 10):
... if num % 2 == 0:
... print("Found an even number", num)
... continue
... print("Found an odd number", num)
...
Found an even number 2
Found an odd number 3
Found an even number 4
Found an odd number 5
Found an even number 6
Found an odd number 7
Found an even number 8
Found an odd number 9