Break keyword – Explained with Examples

Python: Break keyword – Explained with Examples

Break Keyword:

The break statement ends the loop that contains it. Control of the programme is transferred to the statement immediately following the body of the loop.

If the break statement is within a nested loop (a loop within another loop), it will terminate the innermost loop.

Break keyword in Python

We can use break keyword in loops such as while loop and for loop as given below.

1)While loop with break keyword

It can cause a while loop to stop in the middle, even if the condition in the “while statement” remains True.

When the interpreter encounters a break statement, it stops the current loop execution and jumps directly to the code following the loop block.

Example:

Let us use break keyword in while loop .

Let us print all even elements from 1 to n till the number is not divisible by 5.

Below is the implementation:

# given n
n = 100
x = 1
# Using while to iterate till n
while(x <= n):
    # if the x is divisible by 5 then break the loop
    if(x % 5 == 0):
        break
    else:
        print(x)
        # increment the x
        x += 1
print("Break keyword is succesfully executed")

Output:

1
2
3
4
Break keyword is succesfully executed

Explanation:

In the preceding example, the condition in a while statement is True. Because the condition in the ‘while statement’ is always True, this type of loop will iterate over a set of statements indefinitely. We used a break statement to end this loop.

We are printing the value of x and then incrementing it by one in the loop block. Then it determines whether or not x is divisible by 5. When x is divisible by 5, the break statement is invoked. This ends the loop, and control is returned at the end of the while loop.

2)For loop with break Keyword

Example:

Let us use break keyword in for loop .

Given a list and print elements of list till the element of list is not divisible by 2.

Below is the implementation:

# given list
given_list = [4, 2, 8, 4, 1, 3, 7]
# Traverse the list using for loop
for i in range(len(given_list)):
    # if the element is not divisible by 2 then break the loop
    if(given_list[i] % 2 != 0):
        break
    else:
        print(given_list[i])
print("Break keyword executed successfully")

Output:

4
2
8
4
Break keyword executed successfully