continue 语句是 Python 中的一个控制流语句,用于跳过当前循环中剩余的代码,并继续进行下一次循环迭代。下面是关于 continue 语句在 while 循环和 for 循环中的应用示例:

while 循环中使用 continue

while 循环中,continue 语句可以跳过特定条件下的迭代。以下示例展示了在 while 循环中使用 continue

# 在 while 循环中使用 continue
count = 0
while count < 10:
    count += 1
    if count == 3 or count == 7:
        continue
    print(f"Count: {count}")

运行结果如下:

Count: 1
Count: 2
Count: 4
Count: 5
Count: 6
Count: 8
Count: 9
Count: 10

在该示例中,当 count 的值为 3 时,程序会输出一条消息并使用 continue 跳过这一次迭代。因此,数字 3 不会被打印出来。

for 循环中使用 continue

for 循环中,continue 语句同样可以用于跳过特定条件下的迭代。以下示例展示了在 for 循环中使用 continue

# 在 for 循环中使用 continue
fruits = ["apple", "banana", "cherry", "date"]
for fruit in fruits:
    if fruit == "cherry":
        continue
    print(f"Fruit: {fruit}")

运行结果如下:

Fruit: apple
Fruit: banana
Fruit: date

在该示例中,当水果名称为 "cherry" 时,程序会输出一条消息并使用 continue 跳过这个元素的处理,继续下一个迭代。因此,樱桃不会被打印出来。

通过以上示例,说明了在 while 循环和 for 循环中如何使用 continue 语句来跳过当前迭代,继续执行下一个迭代的操作。

以上示例在[小蜜蜂AI网站][https://zglg.work]获取。