ZetCode

Python Continue 关键字

最后修改于 2025 年 2 月 25 日

Python 中的 continue 关键字会跳过当前循环迭代的剩余代码。它将控制权转回循环的开头,开始下一次循环。本教程将介绍 continue 在控制循环执行流程方面的实际用法。

当您需要绕过特定迭代而不退出整个循环时,请使用 continue。与终止循环的 break 不同,continue 只会跳过一次迭代。它在 forwhile 循环中都有效。

跳过偶数

本示例演示了如何在 for 循环中使用 continue 跳过偶数。

skip_evens.py
for num in range(1, 11):
    if num % 2 == 0:
        continue
    print(num, end=' ')

# Output: 1 3 5 7 9

循环处理数字 1-10。当检测到偶数时,continue 会跳过该迭代的打印语句。

过滤列表元素

本示例处理一个包含混合数据类型的列表,并跳过非整数值。

filter_list.py
items = [12, 'apple', 0, 4.5, 'error', 8]

for item in items:
    if not isinstance(item, int):
        continue
    print(f"Processing integer: {item}")

# Output: Processing integer: 12
#         Processing integer: 0
#         Processing integer: 8

continue 通过跳过非整数元素来避免错误。当处理异构数据结构时,这种模式很有用。

While 循环验证

本示例在 while 循环中使用 continue 来处理无效的用户输入。

input_validation.py
while True:
    value = input("Enter positive number: ")
    if not value.isdigit():
        print("Invalid input")
        continue
    if int(value) > 0:
        break

print(f"Valid number: {value}")

检测到非数字输入时,循环会立即重新开始,迫使用户在继续之前提供有效数据。

嵌套循环处理

本示例演示了在嵌套循环中使用 continue,跳过特定的配对组合。

nested_loop.py
for i in range(3):
    for j in range(3):
        if j == i:
            continue
        print(f"({i}, {j})", end=' ')
    print()

# Output: (0, 1) (0, 2) 
#         (1, 0) (1, 2) 
#         (2, 0) (2, 1)

内部循环跳过 j 等于 i 的迭代,从而避免在矩阵模式中出现对角线配对。

跳过元音字母

本示例在处理字符串时使用 continue 跳过元音字母。

skip_vowels.py
text = "Python Programming"
vowels = {'a', 'e', 'i', 'o', 'u'}

for char in text.lower():
    if char in vowels:
        continue
    print(char.upper(), end='')

# Output: P Y T H N   P R G R M M N G

循环将文本转换为大写,同时跳过元音字母。请注意,空格通过 continue 逻辑得以保留。

最佳实践

来源

Python 循环控制文档

本教程演示了 Python 的 continue 语句在各种场景下控制循环执行流程的实际用法。

作者

我的名字是 Jan Bodnar,我是一名充满热情的程序员,拥有丰富的编程经验。我自 2007 年以来一直在撰写编程文章。迄今为止,我已撰写了 1400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出所有 Python 教程