Planet Python

Real Python: How to Exit Loops Early With the Python Break Keyword

The Python `break` statement provides a way to exit loops prematurely, transferring control to the code following the loop. It is applicable to both `for` and `while` loops, allowing for early termination based on certain conditions. The `continue` keyword offers complementary functionality by skipping to the next iteration of the loop. Using `break` outside of a loop results in a SyntaxError, as it's designed specifically for loop control. A primary advantage of `break` is preventing unnecessary iterations by exiting the loop when appropriate. An example involves assessing student test scores and identifying the number of failed tests using a `for` loop and `break`. The `break` statement only exits the innermost loop it resides in, not all loops. It can be useful when processing user input, such as in a number-guessing game. This allows for dynamic loop control based on user actions. The provided example code demonstrates a loop that prints numbers until one exceeds 5, at which point `break` terminates it.
favicon
realpython.com
realpython.com
Image for the article: Real Python: How to Exit Loops Early With the Python Break Keyword
Create attached notes ...