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.
Similar Reads
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
7 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 Python
2 min read
Python return statement A return statement is used to end the execution of the function call and it "returns" the value of the expression following the return keyword to the caller. The statements after the return statements are not executed. If the return statement is without any expression, then the special value None is
4 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 sta
6 min read