Categories

Chapter 2.3: Controlling Loop Execution – Break, Continue

Understanding and using break and continue within loops

In programming, it’s often necessary to have more control over the flow of execution within loops. Python provides two keywords, break and continue, which help to control loop execution.

The break Statement

The break statement is used to exit or “break” a loop prematurely. When encountered inside a loop, the break statement immediately terminates the loop, and program control resumes at the next statement following the loop.

Here’s an example:

for i in range(10):
    if i == 5:
        break
    print(i)

In this code, the loop will break as soon as i equals 5, and thus the numbers printed are 0 through 4.

The continue Statement

The continue statement skips the remaining portion of the loop and immediately moves on to the next iteration of the loop. It does not terminate the loop; instead, it just skips the current iteration.

Here’s an example:

for i in range(10):
    if i == 5:
        continue
    print(i)

In this code, when i equals 5, the continue statement is encountered and the rest of the loop for this iteration (the print statement) is skipped. The loop then moves on to the next iteration (where i equals 6). Thus, the numbers printed are 0 through 4 and 6 through 9.

Note: Be careful when using break and continue in nested loops (loops inside loops), as break and continue affect only the innermost loop in which they are placed.

Summary

The break and continue statements provide powerful ways to control the flow of your loops:

  • Use break when you want to terminate the loop prematurely.
  • Use continue when you want to skip to the next iteration of the loop without executing the rest of the loop body.

By understanding and using these keywords effectively, you can have greater control over your loops and make your Python programs more efficient and readable.

Leave a Reply

Your email address will not be published. Required fields are marked *