In Python, the break
statement is used to exit or terminate a loop prematurely when a certain condition is met. It is commonly used within for
and while
loops to stop the loop execution and transfer control to the next statement after the loop.
Syntax of break
Statement:
break
When the break
statement is executed, it immediately terminates the innermost loop that contains it. The code after the break
statement (within the loop) is skipped, and the control is transferred to the first statement following the loop.
Example 1: Using break
in a while
loop
In this example, the loop will keep running until the user enters the correct password. If the user enters the wrong password three times, the loop will terminate due to the break
statement.
attempts = 0
while attempts < 3:
password = input("Enter your password: ")
if password == "secret":
print("Access granted.")
break
else:
print("Incorrect password. Try again.")
attempts += 1
else:
print("Too many failed attempts.")
In this case:
- The
while
loop continues to ask for the password until the user enters the correct one. - If the password is correct, the
break
statement is executed, and the loop is exited. - If the user reaches the maximum number of attempts (3), the
else
block of thewhile
loop will execute, printing “Too many failed attempts.”
Example 2: Using break
in a for
loop
Here’s an example where the loop searches for a specific number in a list, and stops searching once it finds the number.
numbers = [1, 2, 3, 4, 5, 6, 7]
search_for = 5
for number in numbers:
if number == search_for:
print(f"Found {search_for}!")
break
else:
print(f"{search_for} not found in the list.")
In this case:
- The
for
loop iterates through thenumbers
list. - Once it finds the number
5
, thebreak
statement is executed, and the loop exits immediately. - If
5
was not found, theelse
block (which is executed only if the loop completes without abreak
) prints “5 not found in the list.”
Example 3: Nested Loops with break
In case of nested loops, the break
statement only terminates the innermost loop. If you need to break out of multiple loops, you would need a different approach, such as using a flag or breaking from the outer loop using return
(if inside a function).
for i in range(3):
for j in range(3):
print(f"i = {i}, j = {j}")
if j == 1:
break # Breaks only the inner loop (for j)
In this case:
- The outer loop (with
i
) runs from 0 to 2. - The inner loop (with
j
) runs from 0 to 2, but thebreak
statement exits the inner loop whenj == 1
.
Important Notes:
- Break only exits the loop: It does not exit from functions or the entire program. It only affects the loop it is in.
else
with loops: Theelse
block of a loop is executed only if the loop completes without encountering abreak
statement.- Nested loops: The
break
only terminates the innermost loop. For exiting multiple loops, you might need additional logic (e.g., flags orreturn
in functions).
Conclusion:
The break
statement in Python is a useful tool to control the flow of loops by exiting them early when a specific condition is met. It can be applied in both for
and while
loops to improve the efficiency of your program by preventing unnecessary iterations.