When a specific requirement is satisfied, the break statement is used to end the loop. For as long as the loop condition evaluates to true, as we have learnt in earlier tutorials (for loop and while loop), a loop is used to repeatedly iterate a group of statements. The break statement is typically used inside of a loop together with an if statement so that the loop will end when a specific condition (specified in the if statement) returns true.
Let’s take a search for an element in a list as an example. To do this, we would run a loop from the list’s first element to its last element. When an entry is found, we may use the break statement to end the loop immediately rather than continuing it until the end of the list. Break statements will assist us accomplish this (we will see this example programmatically in the example section below).
Python’s break statement syntax
Python’s break statement uses syntax that is comparable to that of Java.
A break statement example
Among this illustration, we are looking for the number “88” in the provided list of integers. It is necessary to show every number up until the number “88” is found, at which point the loop must be broken and the remaining numbers must not be shown.
# program to display all the elements before number 88 for num in [11, 9, 88, 10, 90, 3, 19]: print(num) if(num==88): print("The number 88 is found") print("Terminating the loop") break
11 9 88 The number 88 is found Terminating the loop
Always pair a break statement with an if statement to ensure that only the break statement is encountered when the ‘if’ condition is true. If you do not utilize it with a “if” statement, the loop would always end after the first iteration because the break statement would be encountered.