Loop Control Statements
6. The Exit Strategy and the Second Chance
Finally, let's discuss loop control statements: `break` and `continue`. These statements allow you to modify the normal flow of a loop, either by terminating it prematurely or skipping over certain iterations. Think of them as emergency exits and second chances, providing you with the flexibility to handle unexpected situations or optimize your code.
The `break` statement is like hitting the emergency stop button. It immediately terminates the loop and transfers control to the next statement after the loop. This is useful when you've found what you're looking for, encountered an error, or need to exit the loop for any other reason.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]for number in numbers: if number > 5: break print(number)
In this example, the loop iterates over the `numbers` list. When the `number` is greater than 5, the `break` statement is executed, terminating the loop. As a result, only the numbers 1 through 5 are printed. You could also use it in a `while` loop if some certain condition is fulfilled!
The `continue` statement, on the other hand, is like getting a second chance. It skips the rest of the current iteration and jumps to the next iteration of the loop. This is useful when you want to skip over certain elements or conditions without terminating the loop entirely. Both statements are helpful to create more complex loops and solve a broader variety of problems!
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]for number in numbers: if number % 2 == 0: continue print(number)
In this example, the loop iterates over the `numbers` list. If the `number` is even, the `continue` statement is executed, skipping the `print` statement and moving on to the next number. As a result, only the odd numbers are printed. They are powerful tools, so you should use them wisely!