0
0
Pythonprogramming~5 mins

Break vs continue execution difference in Python - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Break vs continue execution difference
O(1)
Understanding Time Complexity

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?

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for loop running up to n times.
  • How many times: Actually runs only until i == 5 because of break, so up to 6 times.
How Execution Grows With Input

Because the loop stops early at 5, the number of steps does not grow with n after a point.

Input Size (n)Approx. Operations
106 (stops at i=5)
1006 (still stops at i=5)
10006 (still stops at i=5)

Pattern observation: The loop runs a fixed number of times regardless of input size because of break.

Final Time Complexity

Time Complexity: O(1)

This means the loop runs a fixed number of times no matter how big n gets, thanks to break.

Common Mistake

[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.

Interview Connect

Understanding how break and continue affect loops helps you explain code efficiency clearly and shows you know how to control loops smartly.

Self-Check

"What if we removed the break statement? How would the time complexity change?"