Python continue 语句

Python3 循环语句 Python3 循环语句


continue 是 Python 中用于跳过本次循环、进入下一次迭代的关键字。

break 不同,continue 不会终止整个循环,只是跳过当前这一次循环的剩余代码。

单词释义continue 意为"继续",跳过当前迭代,进入下一次。


基本语法与参数

continue 是一个独立的语句,不需要任何参数。

语法格式

for item in iterable:
    if 跳过条件:
        continue
    # 处理代码

使用场景

  • 跳过特定元素: 满足条件时跳过处理。
  • 过滤数据: 排除不符合条件的数据。
  • 简化逻辑: 将"不处理"的条件提前,减少嵌套。

实例

示例 1:跳过偶数

实例

# 打印 1-10 的奇数
for i in range(1, 11):
    if i % 2 == 0:
        continue  # 跳过偶数
    print(i, end=" ")
print()
# 输出: 1 3 5 7 9

运行结果预期:

1 3 5 7 9

代码解析:

  1. 当 i 是偶数时,执行 continue,跳过后面的 print。
  2. 当 i 是奇数时,正常执行 print。

示例 2:过滤列表元素

实例

# 过滤掉空值和 None
data = ["apple", None, "", "banana", " ", "cherry"]

# 方式1:使用 continue
result = []
for item in data:
    if not item:  # 空字符串或 None 为 False
        continue
    result.append(item)

print(result)  # 输出: ['apple', 'banana', ' ', 'cherry']

# 方式2:只处理有效的
print("有效数据:")
for item in data:
    if item:  # 非空非 None
        print(f"- {item}")

运行结果预期:

['apple', 'banana', ' ', 'cherry']
有效数据:
- apple
- banana
-
- cherry

continue 可以用于过滤数据,排除不需要的元素。

示例 3:在 while 循环中使用

实例

# 模拟跳过特定数字
n = 0
while n < 10:
    n += 1
    if n == 5 or n == 7:
        continue  # 跳过 5 和 7
    print(n, end=" ")
print()
# 输出: 1 2 3 4 6 8 9 10

运行结果预期:

1 2 3 4 6 8 9 10

continue 在 while 循环中的作用相同。

示例 4:简化代码逻辑

实例

# 使用 continue 简化逻辑
numbers = [1, 2, -3, 4, -5, 6, -7]

# 不使用 continue(嵌套较深)
print("正数(方式1):")
for n in numbers:
    if n > 0:
        print(n)

print("\n正数(方式2)- 使用 continue):")
for n in numbers:
    if n <= 0:
        continue
    print(n)

print("\n负数:")
for n in numbers:
    if n >= 0:
        continue
    print(n)

运行结果预期:

使用 continue 可以使代码更扁平,减少嵌套。

示例 5:嵌套循环中的 continue

实例

# continue 只影响当前循环
for i in range(1, 4):
    for j in range(1, 4):
        if j == 2:
            continue  # 跳过内层本次迭代
        print(f"({i},{j})", end=" ")
    print()

运行结果预期:

(1,1) (1,3)
(2,1) (2,3)
(3,1) (3,3)

continue 只跳过包含它的最内层循环的当前迭代。


Python3 循环语句 Python3 循环语句