Member-only story
Hi everyone, welcome back. Today, we will be going over the break statement in Python and see how it works. The break statement is used to break out of a loop. This can be done in either a for loop or a while loop, we will see an example of both. With this introduction out of the way, let’s get into it.
Example: Breaking Out of a For Loop
Let’s see an example of us breaking out of a for loop:
for x in range(5):
if x == 3:
break
print(x)Output:
0
1
2
As we can see the example above, we are executing our break statement when our x variable reaches 3. Looking at the output, we see that we looped through the values of 0, 1, and 2, but nothing else. This verifies that we have broken out of our for loop after x was equal to 3.
Example: Breaking Out of a While Loop
Now, let’s see an example of us breaking out of a while loop:
x = 0
while x < 5:
if x == 3:
break
print(x)
x += 1Output:
0
1
2
Similar to the for loop example, we are executing our break statement when our x variable reaches 3. We can see in the output that we have successfully looped through values 0, 1, and 2, but nothing else, verifying that we have broken out of the while loop.
Conclusion
This is it for the break statement examples. It’s a statement that is used to break out of loops for any reason needed. I hope this helps. Thanks for reading.