break and continue statements in Python
In Python, both break and continue are loop control statements, but they behave differently.
1. break statement The break statement is used to terminate the loop entirely when a condition is met. After breaking, the program continues with the first line of code after the loop.
Syntax
for item in sequence:
if condition:
break Example: Example with for loop.
Python
for i in range(1, 10):
if i == 5:
print("Breaking the loop at:", i)
break
print(i) Output: 1
2
3
4
Breaking the loop at: 5
Here, the loop stops completely when i == 5.
2. continue Statement The continue statement is used to skip the current iteration and move to the next iteration of the loop. It does not terminate the loop — it just skips whatever comes after continue for that iteration.
Syntax
for item in sequence:
if condition:
continue Example: Example with for loop.
Python
for i in range(1, 10):
if i == 5:
print("Skipping number:", i)
continue
print(i) Output: 1
2
3
4
Skipping number: 5
6
7
8
9
Here, i == 5 is skipped, but the loop continues with 6.