Python continue 语句
- 0Python 的 continue 语句用于跳过循环的当前迭代的执行。
- 我们不能在循环外部使用 continue 语句,它会抛出错误“ SyntaxError: 'continue' outside loop ”。
- 我们可以在 for 循环 和 while 循环中使用 continue 语句。
- 如果嵌套循环中存在 continue 语句 ,则只会跳过内层循环的执行。
- “continue”是 Python中的保留关键字。
- 通常,continue 语句与if 语句一起使用,以确定跳过当前循环执行的条件。
continue语句的流程图

Python continue 语句语法
continue 语句的语法是:
python
continue我们不能在 continue 语句中使用任何选项、标签或条件。
Python continue 语句示例
让我们来看一些在 Python 中使用 continue 语句的例子。
1. 继续执行 for 循环
假设我们有一个整数序列。如果序列中的值为 3,则需要跳过该序列的处理。我们可以使用 for 循环和 continue 语句来实现这个场景。
python
t_ints = (1, 2, 3, 4, 5)
for i in t_ints:
if i == 3:
continue
print(f'Processing integer {i}')
print("Done")输出:

2. 在 while 循环中使用 continue 语句
以下是一个在 while 循环中使用 continue 语句的简单示例。
python
count = 10
while count > 0:
if count % 3 == 0:
count -= 1
continue
print(f'Processing Number {count}')
count -= 1输出:

3. 嵌套循环中的 continue 语句
假设我们有一个元组列表需要处理。该元组包含整数。在以下情况下,应跳过处理步骤。
- 如果元组的大小大于 2,则跳过对该元组的处理。
- 如果整数为 3,则跳过执行。
我们可以使用嵌套的 for 循环来实现这个逻辑。为了满足上述条件,我们需要使用两个 continue 语句。
python
list_of_tuples = [(1, 2), (3, 4), (5, 6, 7)]
for t in list_of_tuples:
# don't process tuple with more than 2 elements
if len(t) > 2:
continue
for i in t:
# don't process if the tuple element value is 3
if i == 3:
continue
print(f'Processing {i}')输出:

为什么Python不支持带标签的continue语句?
许多流行的编程语言都支持带标签的 continue 语句。它主要用于在嵌套循环中跳过外层循环的迭代。然而,Python 不支持带标签的 continue 语句。
PEP 3136 旨在为 continue 语句添加标签支持。但是,该提案被否决了,因为这种情况非常罕见,而且会给语言增加不必要的复杂性。我们始终可以在外层循环中编写条件来跳过当前执行。
Python 的 continue、break 和 pass 对比
| continue | break | pass |
|---|---|---|
continue 语句只会跳过循环的当前迭代。 | break 语句会终止循环。 | pass 语句用于写入空代码块。 |
continue 语句只能在循环内部使用。 | break 语句只能在循环内部使用。 | pass 可以在 Python 代码中的任意位置使用。 |