The break statement is used to exit a loop immediately.
When Python encounters a break statement, it stops the loop and continues with the next statement after the loop.
The break statement can be used in both for and while loops.
Syntax
break
Break in a For Loop
Example:
for i in range(1, 6):
if i == 4:
break
print(i)
Output:
1
2
3
The loop stops when i becomes 4.
Break in a While Loop
Example:
i = 1
while i <= 5:
if i == 4:
break
print(i)
i += 1
Output:
1
2
3
Break with Lists
Example:
fruits = ["Apple", "Banana", "Mango", "Orange"]
for fruit in fruits:
if fruit == "Mango":
break
print(fruit)
Output:
Apple
Banana
Break After Printing
Example:
for i in range(1, 6):
print(i)
if i == 4:
break
Output:
1
2
3
4
Using Break in User Input
Example:
while True:
name = input("Enter your name: ")
if name == "exit":
break
print("Hello", name)
Output:
Enter your name: John
Hello John
Enter your name: exit
The loop stops when the user enters exit.
Break in Nested Loops
Example:
for i in range(1, 4):
for j in range(1, 4):
if j == 2:
break
print(i, j)
Output:
1 1
2 1
3 1
The break statement only exits the inner loop.
Difference Between Break and Continue
break stops the entire loop.
Example:
for i in range(5):
if i == 3:
break
print(i)
Output:
0
1
2
continue skips the current iteration.
Example:
for i in range(5):
if i == 3:
continue
print(i)
Output:
0
1
2
4
Practical Example
Search for a number in a list.
Example:
numbers = [10, 20, 30, 40, 50]
for number in numbers:
if number == 30:
print("Number Found")
break
Output:
Number Found
Summary
- The
breakstatement exits a loop immediately. - It can be used in both
forandwhileloops. - Code after
breakinside the loop is not executed. - In nested loops,
breakonly exits the current loop. - Use
breakwhen you want to stop a loop based on a condition.