Python Break Statement

In Python, the break is a keyword used to prematurely exit a loop, before the loop iterates through all the elements or met its condition. When we execute the break statement, the program immediately terminates the loop, shifting the control to the next line of code after the loop. The break is commonly used in the cases where we need to exit the loop for a given condition.

Syntax of the Python Break Statement:

The syntax of the break statement in Python is given below:

 # jump statement  

break;

    When executed, break causes the loop to terminate and proceeds to the next line of code. In the case of nested loops, break affects only the innermost loop.

    Simple Python Break Statement Example

    Here is a simple example to demonstrate how the break statement works in Python.

    Example

    # Loop through numbers from 1 to 10    
    for num in range(1, 11):    
        if num == 6:  
            break  # breaking the loop at 6  
        print(num)  

    Output:

    1
    2
    3
    4
    5
    

    In this example, we loop through the numbers from 1 to 10. We have used the if-statement to execute the break statement when num = 6.

    As a result, the number from 1 to 5 is printed and the loop terminates when it reaches 6.

    Flowchart of the break Statement in Python

    The following is the flowchart of the Python break statement:

    Python Break Statement

    Step 1: Start the loop

    Step 2: Check the loop condition

    Step 3: If the loop condition is False, exit the loop.

    Step 4: If the loop condition is True, proceed to the loop body.

    Step 5: Inside the loop, evaluate a condition to decide whether to break.

    Step 6: If the break condition is True, execute the break statement – immediately exit the loop.

    Step 7: If the break condition is False, continue executing the loop body.

    Step 8: After completing the current iteration – Go to the next iteration.

    Step 9: Repeat steps 2-8 until the loop ends naturally or via break

    Different Examples of the break Statement

    Let us now see some more examples showing the use of the break statement in Python.

    Example 1: Break Statement with for Loop

    In Python, a ‘for’ loop is used to iterates over a given sequence (e.g., list, tuple, string or range), and executes a block of code for each item in the sequence. We can use the break statement within the ‘for’ loop in order to terminate the loop before it iterates over all elements, on the basis of a specified condition.

    We will take a look an example show how to find an element from a list using the for-loop and the break statement.

    Example

    # given list  
    fruit_basket = ['apple', 'mango', 'banana', 'orange', 'kiwi', 'watermelon', 'blueberries']  
      
    # using the for loop to iterate through the list  
    for index, fruit in enumerate(fruit_basket):  
        # if the fruit is equal to kiwi, then break the loop  
        if fruit == 'kiwi':  
            print("Fruit found!")  
            break   # break statement  
      
    # printing the index of the located element  
    print("Located at index =", index) 

    Output:

    Fruit found!
    Located at index = 4
    

    Explanation:

    In the above example, we are given a list consisting of some fruits. We used the ‘for’ loop to iterate through the list. We used the enumerate() function to add a counter to the list. Inside the loop, we used the ‘if’ statement to check if the current element is ‘kiwi’. We then break the loop using the ‘break’ statement. At last, we printed the index value of the located element.

    Example 2: Break Statement with While Loop

    In Python, a ‘while’ loop repeatedly executes a code block as long as a particular condition is True. We can use the break statement within a while loop in order to exit the loop on the basis of dynamic conditions that may not be known in advance.

    Let us see an example to understand how to use the break statement with the while loop.

    Example

    # initializing the counter  
    count = 1  
      
    # usign the while loop  
    while True:  
      
        print("Count:", count)  
        # if the counter's value is 5, then break the loop  
        if count == 5:  
            print("Condition met! Exiting loop.")  
            break # using the break statement  
        # incrementing the counter by 1  
        count += 1  

    Output:

    Count: 1
    Count: 2
    Count: 3
    Count: 4
    Count: 5
    Condition met! Exiting loop.
    

    Explanation:

    In this example, we initialize a variable, ‘count’ with 1 and used the ‘while’ loop that will run infinitely until the condition is True. Inside the ‘while’ loop, we printed the current value of the ‘count’ variable. We used the ‘if’ conditional statement to check if count’s value is 5 and used the ‘break’ statement to break the loop. At last, we incremented the value of the variable by 1.

    Example 3: Break Statement with Nested Loop

    In Python, nested loops are the loops within loops. It allow us to perform more complex iterations, like looping over multi-dimensional data structures. While using the break statement within nested loops, it is important to understand its scope.

    • Innermost Loop Exit: A break statement will only exit the loop in which it is directly placed.
    • Exiting Multiple Loops: In order to exit multiple levels of nested loops, we need to use additional strategies like adding flags, or encapsulating loops within functions.

    Here is an example of using the break statement in nested loops to search for a number in a 2D list:

    Example

    # given 2D list  
    matrix = [  
        [10, 15, 20],  
        [25, 30, 35],  
        [40, 45, 50]  
    ]  
    # element to be searched  
    target = 30  
      
    found = False  # Flag to track if the number is found  
      
    # using the for nested loop  
    for row in matrix:  
        for num in row:  
            # if the current element is equal to the target value, set flag to True and break the loop        
            if num == target:  
                print(f"Number {target} found! Exiting loops.")  
                found = True  
                break  # using break statement  
        # exiting the outer loop  
        if found:  
            break  

    Output:

    Number 30 found! Exiting loops.
    

    Explanation:

    In this example, we are given a 2D list and a value to be searched in the list. We initialized a flag as False and used the nested ‘for’ loop to traverse the elements of the 2D list. We then used the ‘if’ statement to check for the target value in the list and used the ‘break’ statement to break the inner loop, once found. Then we again used the ‘break’ statement to exit the outer loop.

    Conclusion

    Python provides the break statement which helps programmers execute loop termination based on specific conditions. The break statement functions best at preventing waste in for loops and while loops and nested loops to enhance their speed. Multiple conditions exist for using break in nested loops because the exit command affects only the innermost loop thus requiring supplementary logic to terminate outer loops. The controlled use of break improves program efficiency by making the expression best suited for search operations and data processing and real-time monitoring needs.

    Comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *