Table of Contents
ToggleThe break statement in Python is used to exit from the current loop before it has iterated over all items. It can be used in both for and while loops and is often used when you want to stop execution based on a specific condition.
The syntax for the break statement is as follows:
looping statement:
condition check:
break
Here’s an example of how the break statement works inside a for loop. This loop iterates over the string ‘Python’ and breaks the loop when the letter ‘h’ is encountered:
for letter in 'Python':
if letter == 'h':
break
print("Current Letter:", letter)
print("Good bye!")
Output:
Current Letter: P
Current Letter: y
Current Letter: t
Good bye!
Similarly, the break statement can be used in a while loop to stop the loop when a specified condition is met:
var = 10
while var > 0:
print('Current variable value:', var)
var = var - 1
if var == 5:
break
print("Good bye!")
Output:
Current variable value: 10
Current variable value: 9
Current variable value: 8
Current variable value: 7
Current variable value: 6
Good bye!
The break statement can also be used inside nested loops. If it’s used in the inner loop, only that loop is interrupted. However, if the break is used in the outer loop, both loops are stopped. Here’s an example:
no = 33
numbers = [11, 33, 55, 39, 55, 75, 37, 21, 23, 41, 13]
for num in numbers:
if num == no:
print('Number found in list')
break
else:
print('Number not found in list')
Output:
Number found in list
The break statement is a useful tool for controlling loop execution and making your program more efficient by terminating loops prematurely when certain conditions are met. Use it wisely to enhance the performance and readability of your code.
