Python break Statement with Examples


How to Use the break statement in Python

In this tutorial, you'll learn what the break statement is in Python and how to use it.

What is the use of the break statement in Python?

As you know, loops iterate over a block of code until it meets a specified condition. However, in some cases, you need to terminate the loop and resume to the next statement following the loop.

To terminate a loop and then continue to the next statement of the code, we use the break statement.

The break Statement Syntax

The syntax of the break statement is as follows:

break

Note that break may only occur nested in the while loop statement or for loop statement.

Using break Statement with the while Loop

The while loop iterates over a block of code until it meets a specified condition.
Let's take a look at an example:

count = 10
while count > 0:
    print (count)
    count -= 1

Output:

10
9
8
7
6
5
4
3
2
1

As you can see, the while loop runs and prints the value of the count variable until it is 0.

Now, let's take a look at an example of using the break statement with a while loop to exit the loop before it meets a specified condition:

count = 10
while count > 0:
    if count == 4:
        break
    print (count)
    count -= 1

Output:

10
9
8
7
6
5

As you can see, the while loop runs and prints the value of the count variable, and exits when the count is equal to 4.

Using break Statement with the for Loop

Like the while loop, you can use the break statement to exit the for loop statement and continue execution at the next statement following the for loop block.

Let's take a look at an example of using the for loop statement without the break statement:

fruits = ["Apple""Grape""Mango""Melon""Kiwi""Orange""Watermelon"]
for fruit in fruits:
    print(fruit)

Output:

Apple
Grape
Mango
Melon
Kiwi
Orange
Watermelon

But with the break statement, the program will like this:

fruits = ["Apple""Grape""Mango""Melon""Kiwi""Orange""Watermelon"]
for fruit in fruits:
    print(fruit)
    if fruit == "Melon":
         break

count = 0 #next block of code

When the fruit is equal to Melon, the program exits the loop and continues with the next statement.

Output:

Apple
Grape
Mango
Melon

In this tutorial, you've learned what the break statement is in Python and how to use it. In Python, we the break statement to terminate the loop and then continue with the next statement following the loop block. To skip the current iteration and continue execution with the next iteration, use the continue statement.

Leave a Reply

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