Python Break Statement: How to Exit a Loop and Improve Code Efficiency

Python Break Statement: How to Exit a Loop and Improve Code Efficiency

6 mins read468 Views Comment
Vikram
Vikram Singh
Assistant Manager - Content
Updated on Sep 6, 2024 16:11 IST

Learn how to improve the efficiency of your Python code by using the “break” statement to exit a loop prematurely. Our tutorial explains the syntax and usage of the “break” statement and provides examples to help you understand how it can be applied in real-world situations.

2023_02_MicrosoftTeams-image-182.jpg

Python break statement is one of the most useful features which is used to terminate a loop early. This article will discuss the break statement in Python, how to use it, and some use cases.

Table of Content

Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

– / –
40 hours
– / –
5 days
– / –
3 days
3 K
3 weeks
– / –
4 days
– / –
20 hours
– / –
2 months
Free
6 weeks

What is Break Statement?

The break statement is a control statement in Python that allows you to exit a loop prematurely. It can be used with the for and while loops, and when executed, the loop stops executing, and control passes to the statement immediately following the loop. The break statement is typically used when you need to search for a specific value or condition in a loop, and you want to stop the loop as soon as you find what you’re looking for.

What is Programming What is Python
What is Data Science What is Machine Learning

Flowchart of Break Statement in Python

2023_02_image-116.jpg

Syntax

The syntax for the break statement is very simple. You use the keyword “break” followed by a semicolon (;). Here’s an example of how to use the break statement in a for loop:


 
for i in range(10):
if i == 5:
break
print(i)
Copy code

Output

2023_02_image-117.jpg

In this example, we’re using a for loop to iterate over a range of numbers from 0 to 9. The if statement inside the loop checks if the current value of i equals 5. If it is, the break statement is executed, and the loop is terminated. If the current value of i is not equal to 5, the loop continues executing, and the value of i is printed to the console.

Must Read: Difference Between Python Break and Continue Statement

How to use Break Statement in Python

Now that you know what the break statement is and what it does, let’s look at how to use it in your Python programs. It can be used with any loop in Python, including for loops, while loops, and nested loops.

Using the break statement in a for loop

The for loop is one of the most commonly used loops in Python, which is used to iterate over a sequence of values, such as a list or a range of numbers. Here’s an example of how to use the break statement in a for loop:


 
fruits = ['apple', 'banana', 'cherry', 'orange', 'pineapple']
for fruit in fruits:
if fruit == 'orange':
break
print(fruit)
Copy code

Output

2023_02_image-118.jpg

In this example, we’re iterating over a list of fruits using a for loop. The if statement inside the loop checks if the current value of the fruit equals ‘orange’, and once the value of the fruit is equal to orange, the break statement will be executed, and the loop will be terminated. If the current value of the fruit is not equal to ‘orange’, the loop continues executing, and the value of the fruit is printed to the console.

Must Read: For loop in Python

Must Read: For Loop in Python (Practice Problem)

Using the break statement in a while loop

The while loop is another commonly used loop in Python which is used to execute a block of code as long as a specific condition is true. Here’s an example of how to use the break statement in a while loop:


 
i = 0
while i < 10:
if i == 5:
break
print(i)
i += 1
Copy code

Output

2023_02_image-120.jpg

In this example, we’re using a while loop to iterate over a range of numbers from 0 to 9. The if statement inside the loop checks if the current value of i equals 5. If it is, the break statement is executed, and the loop is terminated. If the current value of i is not equal to 5, the loop continues executing, and the value of the fruit is printed to the console.

Must Read: Python While Loop

Programming Online Courses and Certification Python Online Courses and Certifications
Data Science Online Courses and Certifications Machine Learning Online Courses and Certifications

Using the break statement in nested loops

In addition to using the break statement in a single loop, it can also be used in nested loops. A nested loop is a loop that is inside another loop. Here’s an example of how to use the break statement in a nested loop: the break statement will only terminate the innermost loop it is executed in. Here’s an example:


 
for i in range(3):
for j in range(3):
if i == j:
break
print(i, j)
Copy code

Output

2023_02_image-121.jpg

In this example, we’re using a nested for loop to iterate over two ranges of numbers. The outer loop iterates over the range of numbers from 0 to 2, and the inner loop also iterates over the range of numbers from 0 to 2. The if statement inside the inner loop checks if the current value of i equals the current value of j. If it is, the break statement is executed, and the inner loop is terminated. If the current value of i is not equal to that of j, the loop continues executing, and the values of i and j are printed to the console.

Using the break statement with try-except

The break statement can also be used with try-except blocks in Python. A try-except block is used to handle errors that occur during the execution of a program. Here’s an example of how to use the break statement with a try-except block:


 
while True:
try:
x = int(input("Enter a number: "))
break
except ValueError:
print("Invalid input. Try again.")
print("You entered:", x)
Copy code

Output

2023_02_image-122.jpg

In this example, we use a while loop to ask the user to enter a number. The try block inside the loop converts the user’s input to an integer using the int() function. If the input is not a valid integer, a ValueError is raised, and the except block catches the error and prints a message to the console. The loop then continues and asks the user to enter another number. If the input is a valid integer, the break statement is executed, and the loop is terminated. The value of x is then printed to the console.

Must Read: Python try-except

Use cases for Break Statements

  1. Searching for an item in a list: If you’re searching for an item in a list and you find it, you can use the break statement to exit the loop early.
  2. Checking for a specific condition: You can use the break statement to stop iterating through a loop once a certain condition is met.
  3. Avoiding an infinite loop: Sometimes, a loop may never terminate due to an error in the code. In this case, you can use the break statement to exit the loop and prevent the program from running indefinitely.

Must Read: All About Python Lists Method

Must Read: Python List Program for Beginner

Also Read: Getting started with Python Strings

Also Read: String Formatting in Python

Conclusion

In this article, we have discussed how to use break statement with the help of different examples. We also discussed different use cases where we can use break statement in python.

Keep Learning!!

Keep Sharing!!

Top Trending Article

Top Online Python Compiler | How to Check if a Python String is Palindrome | Feature Selection Technique | Conditional Statement in Python | How to Find Armstrong Number in Python | Data Types in Python | How to Find Second Occurrence of Sub-String in Python String | For Loop in Python |Prime Number | Inheritance in Python | Validating Password using Python Regex | Python List |Market Basket Analysis in Python | Python Dictionary | Python While Loop | Python Split Function | Rock Paper Scissor Game in Python | Python String | How to Generate Random Number in Python | Python Program to Check Leap Year | Slicing in Python

Interview Questions

Data Science Interview Questions | Machine Learning Interview Questions | Statistics Interview Question | Coding Interview Questions | SQL Interview Questions | SQL Query Interview Questions | Data Engineering Interview Questions | Data Structure Interview Questions | Database Interview Questions | Data Modeling Interview Questions | Deep Learning Interview Questions |

About the Author
author-image
Vikram Singh
Assistant Manager - Content

Vikram has a Postgraduate degree in Applied Mathematics, with a keen interest in Data Science and Machine Learning. He has experience of 2+ years in content creation in Mathematics, Statistics, Data Science, and Mac... Read Full Bio