Jump Statements: break, continue, and pass
Jump statements are special keywords in Python that alter the normal flow of a loop. They give you the power to exit a loop early, skip part of a loop, or do nothing at all.
Mastering break, continue, and pass will allow you to write highly efficient, elegant, and readable code.
The Three Jump Statements
1. The `break` Statement
break: Exiting a Loop Early
The break statement immediately terminates the innermost loop it is currently in. As soon as Python runs a break, the program’s control jumps directly to the very next line of code written after the loop.
It is most often used to stop a loop when a specific condition has been successfully met, saving your computer from running unnecessary extra steps.
When to Use break:
- When you find the exact item you were searching for.
- When an error occurs that makes continuing the loop completely pointless.
- When the user types an instruction indicating they want to quit.
Example: Finding the First Multiple of 7
Imagine you want to find the very first number divisible by 7 in a list. Once you find it, there is no need to check the remaining numbers:
Example
Output:
break vs. continue: A Head-to-Head Comparison
| Feature | break | continue |
|---|---|---|
| Action | Terminates the entire loop. | Skips the remaining code in the current turn. |
| Control Flow | Jumps to the code after the loop. | Jumps directly to the next iteration of the loop. |
| Analogy | Hitting the “stop” button on a music player. | Hitting the “next track” button. |
Visual Demonstration
Let us see the differences side by side. Run the program below to compare how the loop behaves when it encounters the number 3:
Example
Output:
Understanding when to use break and continue is key to writing clean and efficient loops. Use break to save computer resources when a result has been successfully found, and use continue to simplify your logic by filtering out items you do not need to process.