Python Control Statements: break and continue

1. break

  • The function of break: used to end the entire loop
  • Can only be used in loops; it cannot be used independently
  • In nested loops, it only affects the innermost loop

demo:

In [1]:   name = 'yuque'   ...:    ...:   for x in name:   ...:       print('----')   ...:       if x == 'q':    ...:           break   ...:       print(x)   ...:     ----y----u----

2. continue

  • The function of continue: used to end the current iteration of the loop and immediately execute the next iteration
  • Can only be used in loops; it cannot be used independently
  • In nested loops, it only affects the innermost loop

demo:

In [2]:   name = 'yuque'   ...:    ...:   for x in name:   ...:       print('----')   ...:       if x == 'q':    ...:           continue   ...:       print(x)   ...:     ----y----u--------u----e

3. else

When the loop exits normally without encountering continue or break, the code in else is executed

for i in range(10):    pass    # If break is uncommented, the code in else will not executeelse:    print("yuque")>>>"yuque"

Leave a Comment