In this section, we will learn what the break statement is and how to use it in Python.
Break Statement in Python: What Does break Mean?
The `break` statement is used within the body of loops like `while` and `for` loop in order to break the iteration of that loop before its condition is met.
Basically, the use of `break` statement is for when we want to terminate a loop early.
Note: the break statement is only used on its own and it does not take any value.
Example: while loop break statement
num = 0 while num <100: if num ==50: break num +=1 print(num)
Here, the condition of the loop is to run the body of the loop as long as the value of the `num` variable is less than the value 100. But we can see right when the value of the `num` reached to 50, a call to the `break` statement occurred and so the loop terminated.
As you can see, the break statement terminates the entire loop and not just the current iteration of the loop!
Python break Statement and else Statement
Be aware that if there’s a call to the `break` statement and that loop terminated early, its `else` statement (if any) won’t run anymore. (This is true for both `while` and `for` loops)
Example: python break statement and else statement
num = 0 while num <100: if num ==50: break num +=1 else: print("You won't see this message on the output stream.") print(num)
Output:
50
Example: python break for loop
list1 = ["John","Jack","Omid","Ellen","Elon"] for element in list1: if element == "Ellen": break print(element)
Output:
John Jack Omid
Python break Statement in nested loop
The `break` statement can be used within the body of a for loop or a while loop, no-matter if they are a nested loop or not.
But you should know that using the `break` statement within the body of a nested loop will only break that nested loop! Basically, the parent loop won’t take effect.
Example: nested loop and break statement
list1 = ["John","Jack","Omid","Ellen","Elon"] for element in list1: print(element) for num in range(10): if num ==3: break; print(num)
Output:
John 0 1 2 Jack 0 1 2 Omid 0 1 2 Ellen 0 1 2 Elon 0 1 2