Python continue 语句
Python continue 语句用于跳过 program block 的执行,并将控制权返回到当前循环的开头以开始下一次迭代。遇到时,循环将开始下一次迭代,而不执行当前迭代中的其余语句。
continue 语句与 break 的语句正好相反。它会跳过当前循环中的其余语句,并开始下一次迭代。
continue 语句的语法
looping statement:
condition check:
continue
continue 语句的流程图
continue 语句的流程图如下所示 -
带有 for 循环的 Python continue 语句
在 Python 中,continue 语句允许与 for 循环一起使用。在 for 循环中,您应该包含一个 if 语句来检查特定条件。如果条件变为 TRUE,则 continue 语句将跳过当前迭代并继续循环的下一次迭代。
例让我们看一个例子来了解 continue 语句在 for 循环中是如何工作的。
for letter in 'Python':
if letter == 'h':
continue
print ('Current Letter :', letter)
print ("Good bye!")
执行上述代码时,它会生成以下输出 -
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Good bye!
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Good bye!
带有 while 循环的 Python continue 语句
Python continue 语句与 'for' 循环和 'while' 循环一起使用,以跳过当前迭代的执行并将程序的控制权转移到下一次迭代。
示例:检查质因数
以下代码使用 continue 查找给定数字的质因数。为了找到质因数,我们需要从 2 开始连续除以给定的数字,增加除数并继续相同的过程,直到输入减少到 1。
num = 60
print ("Prime factors for: ", num)
d=2
while num > 1:
if num%d==0:
print (d)
num=num/d
continue
d=d+1
在执行时,此代码将生成以下输出 -
Prime factors for: 60
2
2
3
5
2
2
3
5
在上面的程序中为 num 分配不同的值(比如 75),并测试其质因数的结果。
Prime factors for: 75
3
5
5
3
5
5