Skip to main content
 首页 » 编程设计

python之请解释continue语句

2025年05月04日25落叶无声

谁能解释一下 continue 语句,我一直在尽力按照我的理解来分解它,但所有的努力都是徒劳的。这是我在 python 文档中找到的示例程序,但我无法理解它。

for num in range(2, 10): 
    if num % 2 == 0: 
        print("Found an even number", num) 
        continue 
    else: 
        print("Found a number", num) 

请您参考如下方法:

continue 语句使 Python 跳过循环的当前迭代的其余部分,并跳转到下一次迭代的开头。

参见 this documentation page对于 Python 3。该页面上的原始示例是:

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

当遇到continue时,跳过循环末尾的print,再次执行到for获取下一次迭代。请注意对于偶数,如何打印“找到一个偶数”,但不打印“找到一个数字”。这是因为 continue 跳过了循环体的其余部分。


您对示例的修改 - 插入 else - 使 continue 过时,因为 print("Found a number", num) 无论如何都不会执行(它位于 else)分支中。

通过这种方式,您会发现 continue(以及 break)通常是 if...else 的替代控制流机制.使用哪种取决于情况和风格偏好。