In this article, we will discuss how to use the break keyword in python to break the flow of loops. We will also cover examples of while loop and for loop with a break statement.
“break” statement in python is useful to break the flow of a loop abruptly i.e.
- It can force a while loop to stop in between, even if the condition in “while statement” is still True.
- It can stop a for loop in between even if the sequence in “for loop” is not entirely iterated.
As soon as the interpreter encounters a break statement, it stops the current execution of the loop and jumps directly to the code after the loop block.
Let’s understand by some examples
While loop with a break statement
x = 1 # Infinite While Loop while True: print(x) # If x is 6, then break the loop if x == 6: break x += 1
1 2 3 4 5 6
In the above example, it is using a True as the condition in a while statement. This kind of loop will iterate over a suite of statements forever because the condition in ‘while statement’ is always True. Now to stop this loop, we used a break statement.
In the loop block, we are printing the value of x and then incrementing it by one. Then it checks if the value of x is six or not. As soon as x becomes 6, it calls the break statement. Which stops the loop and control comes at the end of the while loop.
- Python: For Loop – Explained with examples
- For Loop with two variables in Python
- Python: while loop – Explained with examples
- Combine For Loop & if-else statement in Python
For loop with a break statement
sample_str = 'sample_statement' # Iterate over all the characters in string for elem in sample_str: # Id char is e then break the loop if elem == 'e': break print(elem)
s a m p l
In the above example, it is using a for loop to iterate over all the characters of a string. But during iteration, for each character, it checks if it is equal to character ‘e’ or not. As soon as it founds a character that is equal to ‘e’, then it calls the ‘break’ keyword. Which stops the ongoing iteration by the “for loop” & control jumps directly to the end of the loop.
All the characters after the character ‘e’ in the string gets skipped. It is because the ‘break’ statement stopped the for loop abruptly in between.
We can use the break statement in python to stop the iteration of a loop in between.