Python

Python Break

“When an external condition is met, you might have to exit a loop. Alternatively, you might want to bypass a section of the loop and move on to the next execution. To manage these circumstances and have good control over your loop, Python has the break and continue statements. The break statement that Python offers will be specifically covered in this tutorial.”

What is a Break Statement in Python?

Python’s break keyword is used to remove the program’s control from the loop. When there are nested loops, the inner loop is broken first, and then the outer loops are broken using the break command. In other words, the control moves to the next line following the loop when the break is used to stop the program’s current execution

In Python, you can use break in all types of loops, including while, for, and nested. If you use it in nested loops, the innermost loop where you used it will be terminated, and control of the program will then move to the outer loop. In other words, it disrupts the loop’s order, and control is transferred to the first line outside the loop.

Now that the definition of a break statement has been established, it’s time to examine some examples and learn how to apply them. You will use Break in Python with various loops in each situation.

Example 1

Let’s have a look at a for loop example that employs the break statement. The variable number in this brief program has a starting value of 0 (num=0). If the variable number is less than 8, a for statement creates the loop. An if statement that presents the condition that the loop will break if the variable number is equal to the integer 3 is contained within the for loop.

Since it comes after the break statement, the print() statement inside the loop will run every time the for loop iterates until the loop breaks. We have inserted a final print() statement outside of the for loop so that we will know when we have exited the loop. The first print statement will list down the numbers, and the second print statement will display the message “Out of Loop”.

num = 0
for num in range(8):
    if num == 3:
        break  
    print(str(num))
print('Out of loop')

Our output after running this code will be as follows. This demonstrates how the loop ends after the integer number is evaluated to be equal to 3, as instructed by the break instruction in the program. A program exits a loop when the break statement is used.

Example 2

In this example, we are searching for a specific number (45 in our case) in the list of numbers. It is necessary to show every number up until the number “45” is found, at which point the loop must be broken, and the remaining numbers must not be shown. In the code, there are two print statements. If the number is included in the list, the first print statement will display the message “The number is found.” The loop’s termination will be displayed in the second print statement.

for n in [22, 7, 45, 20, 60, 2, 29]:
   print(n)
   if(n==45):
       print("The number is found")
       print("Terminating the loop")
       break

for n in [22, 7, 45, 20, 60, 2, 29]:
   print(n)
   if(n==46):
       print("The number is found")
       print("Terminating the loop")
       break

Here, you can see that the code halts its iteration and displays the message when the given number is located in the list.

Let’s say the program displays every item in the list even if the requested number isn’t included in it. In this instance, we’re trying to find the number “46,” which isn’t on the list. In the program code below, n==46 is used to denote it.

All of the items in the list are displayed in the output, as you can see. The program did not execute the print statements because the specified number was not found.

Example 3

For your help, here is one more example that you can refer to. The break statement is written inside a while loop in this example. You will be asked to write your favorite fruit. Once you stop, the program will terminate. In the code, the while True generates an indefinite loop. When you enter stop, the break statement is executed to end the loop once the condition fav_fruit.lower() == “stop” evaluates to True. For you to type stop, STOP, or stop to end the application, the fav_fruit.lower() function returns the favorite fruit in lowercase.

print('Please enter stop to exit --')
while True:
    fav_fruit = input('Enter your favorite fruit:')
    if fav_fruit.lower() == 'stop':
        break

The list of preferred fruits is seen in the screenshot below. The break command ends the loop when “stop” is entered by the user.

Example 4

This example will discuss the usage of a break statement in a nested loop. The sample contains two for-loops. Both for-loops are iterating within the defined range. We’ve added a specific condition to the second for-loop. This condition says that the for loop should break if the value of the index (in the second for loop) is 2. As a result, the second for-loop will stop the iteration for numbers 2 and 3.

for num in range(2):
    for n in range(6):          
        if n==2:    
            break
        print("The number is ",num,n);

Here you can check the result of the code given above.

Always pair a break statement with an if statement to ensure that just the break statement is encountered when the “if” condition is met. If you do not utilize it with an “if” statement, the loop would always end after the first iteration because the break statement would be encountered.

Conclusion

Getting the hang of the Python break statement will take some practice, despite the fact that it may seem rather simple. It might be beneficial to practice them using a while true loop to gain a better idea of how the flow can be altered. To avoid creating an infinite loop, remember to introduce a break before running it. When you fully grasp the idea, you can run these examples to get a better idea of how you can incorporate the important ideas into your programs.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content