Break vs Continue in Python
Both break and continue are jump statements used inside
loops in Python.
But they behave differently:
break: Immediately exits the loop.continue: Skips the current loop cycle and moves to the next iteration.
Example 1: Using break
for i in range(1, 6):
if i == 3:
break
print(i)
Output:
1
2
Explanation:
- Loop starts from 1 to 5.
- When
i == 3,breakruns → loop stops completely. - So, 3, 4, and 5 are not printed.
Example 2: Using continue
for i in range(1, 6):
if i == 3:
continue
print(i)
Output:
1
2
4
5
Explanation:
- The loop runs from 1 to 5.
- When
i == 3,continueruns → it skips printing 3 and moves to the next number. - All other values are printed normally.
Quick Comparison Table:
| Feature | break |
continue |
|---|---|---|
| Used to | Exit the loop early | Skip current iteration |
| Loop status | Stops completely | Continues with next value |
| Can be used in | for, while |
for, while |
| Example output | 1, 2 (then stops) | 1, 2, 4, 5 (3 skipped) |
Summary:
breakis used when you want to exit the loop completely.continueis used to skip the current loop step and move to the next one.- Both are helpful for controlling how and when loops run.