TutorialAce

Python | Java | MySQL | Excel

Python Tutorial

Python Break Statement with Examples

How to Use a Break Statement in Python

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

What is the use of a break statement in Python?

As you may know, loops iterate over a block of code until a certain condition is reached, but in some cases we need to terminate the loop and resume to next statement following the loop.

In Python, we use the break statement to terminate a loop and continue to the next statement following the loop. The syntax of the break statement is as follows:

break

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

Break with a While Loop

As you may know, a while loop iterates over a block of code while a condition is true. Let's take a look at an example of using a while loop below:

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

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

10
9
8
7
6
5
4
3
2
1

Here is an example of using a break statement with a while loop to exit the loop before a condition is reached:

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

10
9
8
7
6
5

As you can see, the while loop runs and prints the value of the count variable, but exits before the condition is reached.

Break with a For Loop

Like the while loop, the for loop can be made to exit the loop before the given object is finished using the break statement, and continue execution at the next statement following the loop block.

The following code executes and prints all items in the list using a for loop:

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

Apple
Grape
Mango
Melon
Kiwi
Orange
Watermelon

But with the break statement, we can exit the loop and continue execution at the next statement as you can see in the following example:

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

count = 0

The program exits the loop and continue to the next statement when fruit is equal to Melon.

Apple
Grape
Mango
Melon

In this tutorial, we've learned what is break statement in Python and how to use it. In Python, the break statement is used to terminate a loop before a condition is met and continue to the next statement following the loop. If you want to skip the current iteration and continue execution with the next statement, use the continue statement instead.

Leave a Reply