The break statement in Python is used to exit or “break” out of a loop (either a for or while loop) prematurely, before the loop has iterated through all its items or reached its condition. When the break statement is executed, the program immediately exits the loop, and the control moves to the next line of code after the loop.
Basic Example of break
Let’s start with a simple example to understand how break works in a loop.
Python
# Example: Searching for an element in a list
a = [1, 3, 5, 7, 9, 11]
val = 7
for i in a:
if i == val:
print(f"Found at {i}!")
break
else:
print(f"not found")
Explanation:
- The loop iterates through each number in the list.
- When the number 7 is found, it prints a confirmation message and executes break, exiting the loop immediately.
- If the loop completes without finding the number, the else block is executed.
Let’s understand break statement with a loop using a flowchart:
Break Statement with for Loop
A for loop in Python iterates over a sequence (like a list, tuple, string or range) and executes a block of code for each item in that sequence. The break statement can be used within a for loop to exit the loop before it has iterated over all items, based on a specified condition.
Example :
Python
for i in range(10):
print(i)
if i == 6:
break
Break Statement with while Loop
A while loop in Python repeatedly executes a block of code as long as a specified condition is True. The break statement can be used within a while loop to exit the loop based on dynamic conditions that may not be known beforehand.
Example :
Python
cnt = 5
while True:
print(cnt)
cnt -= 1
if cnt == 0:
print("Countdown finished!")
break # Exit the loop
Output5
4
3
2
1
Countdown finished!
Using break in Nested Loops
Nested loops are loops within loops, allowing for more complex iterations, such as iterating over multi-dimensional data structures. When using the break statement within nested loops, it’s essential to understand its scope:
- Innermost Loop Exit: A break statement will only exit the loop in which it is directly placed (the nearest enclosing loop).
- Exiting Multiple Loops: To exit multiple levels of nested loops, additional strategies are required, such as using flags or encapsulating loops within functions.
Suppose we have a list of lists (a 2D list) and we want to find a specific number. Once we find the number, we want to stop searching in both the inner and outer loops.
Example :
Python
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
val = 5
found = False
for r in matrix:
for n in r:
if n == val:
print(f"{val} found!")
found = True
break # Exit the inner loop
if found:
break # Exit the outer loop
In the above example, after iterating till num=7, the value of num will be 8 and the break is encountered so the flow of the execution is brought out of the loop.
Using loops in Python automates and repeats the tasks in an efficient manner. But sometimes, there may arise a condition where you want to exit the loop completely, skip an iteration or ignore some statements of the loop before continuing further in the loop. These can be done by loop control statements called jump statements. Loop control or jump statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control/jump statements.
Python break statement – FAQs
What is a break statement in Python?
A break statement in Python is used to terminate the current loop prematurely when it’s encountered. It immediately stops the iterations and exits the loop. It’s commonly used in for and while loops to halt the execution when a specific condition is met.
for i in range(10):
if i == 5:
break
print(i)
# Output: 0, 1, 2, 3, 4
Does Python break exit all loops?
No, the break statement in Python only exits the nearest enclosing loop, not all loops. To exit multiple nested loops, break must be used in each loop or an alternative structure like raising an exception may be employed.
for i in range(3):
for j in range(3):
if j == 1:
break
print(f"i = {i}, j = {j}")
# Output shows the inner loop breaks when j equals 1.
What is the difference between break and continue statement in Python?
break Statement: Exits the loop entirely.continue Statement: Skips the current iteration and moves to the next iteration of the loop.
for i in range(5):
if i == 3:
continue
print(i)
# Output: 0, 1, 2, 4 (skips 3)
Is break a return statement?
No, the break statement is not a return statement. break only exits a loop, while return exits from a function entirely, optionally passing back a value.
Similar Reads
Python break statement
The break statement in Python is used to exit or "break" out of a loop (either a for or while loop) prematurely, before the loop has iterated through all its items or reached its condition. When the break statement is executed, the program immediately exits the loop, and the control moves to the nex
5 min read
Python pass Statement
Pass statement in Python is a null operation or a placeholder. It is used when a statement is syntactically required but we don't want to execute any code. It does nothing but allows us to maintain the structure of our program. Example Use of Pass Keyword in a FunctionPass keyword in a function is u
3 min read
Python Match Case Statement
Introduced in Python 3.10, the match case statement offers a powerful mechanism for pattern matching in Python. It allows us to perform more expressive and readable conditional checks. Unlike traditional if-elif-else chains, which can become unwieldy with complex conditions, the match-case statement
8 min read
Python Continue Statement
Python Continue Statement skips the execution of the program block after the continue statement and forces the control to start the next iteration. Python Continue StatementPython Continue statement is a loop control statement that forces to execute the next iteration of the loop while skipping the
4 min read
Python - Multi-Line Statements
In this article, we are going to understand the concept of Multi-Line statements in the Python programming language. Statements in Python: In Python, a statement is a logical command that a Python interpreter can read and carry out. It might be an assignment statement or an expression in Python. Mul
3 min read
Jump Statements in Python
In any programming language, a command written by the programmer for the computer to act is known as a statement. In simple words, a statement can be thought of as an instruction that programmers give to the computer and upon receiving them, the computer acts accordingly. There are various types of
4 min read
Nested-if statement in Python
For more complex decision trees, Python allows for nested if statements where one if statement is placed inside another. This article will explore the concept of nested if statements in Python, providing clarity on how to use them effectively. Python Nested if StatementA nested if statement in Pytho
2 min read
Conditional Statements in Python
Conditional statements in Python are used to execute certain blocks of code based on specific conditions. These statements help control the flow of a program, making it behave differently in different situations. If Conditional Statement in PythonIf statement is the simplest form of a conditional st
6 min read
Python Set Exercise
Basic Set ProgramsFind the size of a Set in PythonIterate over a set in PythonPython - Maximum and Minimum in a SetPython - Remove items from SetPython - Check if two lists have at-least one element commonPython program to find common elements in three lists using setsPython - Find missing and addit
2 min read
Python Cheat sheet (2024)
Python is one of the most widely-used and popular programming languages, was developed by Guido van Rossum and released first in 1991. Python is a free and open-source language with a very simple and clean syntax which makes it easy for developers to learn Python. It supports object-oriented program
15+ min read