Python Using break and continue to Control Loops

Document 对象参考手册Python3 Examples

In Python,breakandcontinueare two keywords used to control the flow of loops.breakis used to immediately terminate the entire loop, whilecontinueis used to skip the current iteration and directly proceed to the next iteration.

Below is an example code that demonstrates how to usebreakandcontinueto control loops.

Example

# Example code
for i in range(1, 11):
    if i == 5:
        continue  # Skip the current iteration
    if i == 8:
        break  # Terminate the loop
    print(i)

Code explanation:

  1. for i in range(1, 11):: This is aforloop,istarting from 1 and ending at 10.
  2. if i == 5:: Wheniequals 5, execute thecontinuestatement to skip the current iteration and directly proceed to the next iteration. Therefore, the number 5 will not be printed.
  3. if i == 8:: Wheniequals 8, execute thebreakstatement to immediately terminate the entire loop. Therefore, the number 8 and subsequent numbers will not be printed.
  4. print(i): Print the currentivalue.

Output result:

1
2
3
4
6
7

In this example, the number 5 is skipped, and the number 8 and subsequent numbers are not printed due to thebreakstatement.

Document 对象参考手册Python3 Examples

Other Extensions