Python 简明教程

Python - Continue Statement

Python continue Statement

Python continue 语句用于跳过程序块的执行并将控制权返回到当前 loop 的开头以启动下一次迭代。遇到这种情况时,循环会启动下一次迭代而不执行当前迭代中的剩余语句。

Python continue statement is used to skip the execution of the program block and returns the control to the beginning of the current loop to start the next iteration. When encountered, the loop starts next iteration without executing the remaining statements in the current iteration.

continue 语句正好与 break 相反。它会跳过当前循环中的剩余语句并启动下一次迭代。

The continue statement is just the opposite to that of break. It skips the remaining statements in the current loop and starts the next iteration.

Syntax of continue Statement

looping statement:
   condition check:
      continue

Flow Diagram of continue Statement

continue 语句的流程图如下 −

The flow diagram of the continue statement looks like this −

loop continue

Python continue Statement with for Loop

Python 中,continue 语句允许与 for 循环一起使用。在 for 循环内,您应该包含一个 if 语句以检查特定条件。如果条件变为 TRUE,则 continue 语句将跳过当前迭代并继续进行循环的下一次迭代。

In Python, the continue statement is allowed to be used with a for loop. Inside the for loop, you should include an if statement to check for a specific condition. If the condition becomes TRUE, the continue statement will skip the current iteration and proceed with the next iteration of the loop.

Example

我们来看一个示例来了解 continue 语句如何在 for 循环中工作。

Let’s see an example to understand how the continue statement works in for loop.

for letter in 'Python':
   if letter == 'h':
      continue
   print ('Current Letter :', letter)
print ("Good bye!")

当执行以上代码时,它会产生以下 output -

When the above code is executed, it produces the following output

Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Good bye!

Python continue Statement with while Loop

Python continue 语句与“for”循环以及“while”循环一起使用,以跳过当前迭代的执行并将程序控制权转移到下一次迭代。

Python continue statement is used with 'for' loops as well as 'while' loops to skip the execution of the current iteration and transfer the program’s control to the next iteration.

Example: Checking Prime Factors

以下代码使用 continue 来查找给定数字的质因数。要查找质因数,我们需要连续除以给定的数字,从 2 开始,增加除数,并继续执行相同的过程,直到输入减小到 1 为止。

Following code uses continue to find the prime factors of a given number. To find prime factors, we need to successively divide the given number starting with 2, increment the divisor and continue the same process till the input reduces to 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

On executing, this code will produce the following output

Prime factors for: 60
2
2
3
5

在上述程序中将不同的值(例如 75)分配给 num 并测试其质因数的结果。

Assign different value (say 75) to num in the above program and test the result for its prime factors.

Prime factors for: 75
3
5
5