Python 简明教程
Python - Continue Statement
Python continue Statement
Python continue 语句用于跳过程序块的执行并将控制权返回到当前 loop 的开头以启动下一次迭代。遇到这种情况时,循环会启动下一次迭代而不执行当前迭代中的剩余语句。
continue 语句正好与 break 相反。它会跳过当前循环中的剩余语句并启动下一次迭代。
Python continue Statement with for Loop
在 Python 中,continue 语句允许与 for 循环一起使用。在 for 循环内,您应该包含一个 if 语句以检查特定条件。如果条件变为 TRUE,则 continue 语句将跳过当前迭代并继续进行循环的下一次迭代。
Python continue Statement with while Loop
Python continue 语句与“for”循环以及“while”循环一起使用,以跳过当前迭代的执行并将程序控制权转移到下一次迭代。
Example: Checking Prime Factors
以下代码使用 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
执行后,此代码将会产生以下 output −
Prime factors for: 60
2
2
3
5
在上述程序中将不同的值(例如 75)分配给 num 并测试其质因数的结果。
Prime factors for: 75
3
5
5