Break vs continue execution difference in Python - Performance Comparison
We want to see how using break and continue inside loops affects how long a program runs.
Specifically, we ask: How does the loop's work change when these commands are used?
Analyze the time complexity of the following code snippet.
for i in range(n):
if i == 5:
break
if i % 2 == 0:
continue
print(i)
This code loops from 0 to n-1, stops early if i is 5, and skips printing even numbers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
forloop running up tontimes. - How many times: Actually runs only until
i == 5because ofbreak, so up to 6 times.
Because the loop stops early at 5, the number of steps does not grow with n after a point.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 6 (stops at i=5) |
| 100 | 6 (still stops at i=5) |
| 1000 | 6 (still stops at i=5) |
Pattern observation: The loop runs a fixed number of times regardless of input size because of break.
Time Complexity: O(1)
This means the loop runs a fixed number of times no matter how big n gets, thanks to break.
[X] Wrong: "The loop always runs n times even with break."
[OK] Correct: Because break stops the loop early, the loop may run fewer times than n.
Understanding how break and continue affect loops helps you explain code efficiency clearly and shows you know how to control loops smartly.
"What if we removed the break statement? How would the time complexity change?"