Python break Statement with Examples

How to Use the break statement in Python

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

Related tutorial: Python continue statement

How do you use a break statement in Python?

A loop iterates until a block of code satisfies a specified condition. In some cases, it is necessary to terminate the loop and resume to the next statement following the loop.

To terminate the loop and proceed to the next block of code, use a break statement.

The break Statement Syntax

The syntax of a break statement in Python is as follows:

break

Note that a break statement is only nested within a while loop statement or a for loop statement.

Using the break statement in a while loop

The while loop repeatedly executes a block of code until the specified condition is met.
Let's take a look at an example:

  1. count = 10
  2.  
  3. while count > 0:
  4.  
  5. print (count)
  6.  
  7. count -= 1

Output:

10
 9
 8
 7
 6
 5
 4
 3
 2
 1

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

Now let's see an example of using a break statement that exits the while loop before the specified condition is met.

  1. count = 10
  2. while count > 0:
  3. if count == 4:
  4. break
  5. print (count)
  6. count -= 1

Output:

10
 9
 8
 7
 6
 5

The while loop executes and prints the value of the "count" variable, and it will exit when the "count" variable reaches 4.

Using a break statement in a for loop statement

Like the while loop, the break statement can be used to terminate a for loop statement and continue execution with the next block of code.

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

  1. fruits = ["Apple", "Grape", "Mango", "Melon", "Kiwi", "Orange", "Watermelon"]
  2. for fruit in fruits:
  3. print(fruit)

Output:

Apple
Grape
Mango
Melon
Kiwi
Orange
Watermelon

If we use a break statement, the program will like this:

  1. fruits = ["Apple", "Grape", "Mango", "Melon", "Kiwi", "Orange", "Watermelon"]
  2. for fruit in fruits:
  3. print(fruit)
  4. if fruit == "Melon":
  5. break
  6. count = 0 #next block of code

When the fruit variable is equal to "Melon," the program exits the loop and proceeds to the next code block.

Output:

Apple
Grape
Mango
Melon

Summary

In this tutorial, you have learned what the Python break statement is and how to use it. A break statement is used to terminate a loop and execute the next statement following the loop block. To skip the current iteration and continue execution with the next iteration, use a continue statement.


See also:
Python return Statement with Examples
Python List Methods and Functions with Examples
Python abs() – Absolute Value in Python
Python Factorial – Find the Factorial of a Number
Python min() – Find the Smallest Value in Python

Leave a Comment