Why while loop is needed in Python - Performance Analysis
We want to see how the time a program takes changes when it uses a while loop.
How does the number of steps grow as the loop runs more times?
Analyze the time complexity of the following code snippet.
count = 0
while count < n:
print(count)
count += 1
This code prints numbers from 0 up to n-1 using a while loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The print statement inside the while loop.
- How many times: It runs once for each number from 0 to n-1, so n times.
Each time n grows, the loop runs more times, adding more print steps.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: The number of steps grows directly with n. Double n, double the steps.
Time Complexity: O(n)
This means the time grows in a straight line with the size of n.
[X] Wrong: "The while loop runs only once no matter what n is."
[OK] Correct: The loop runs as many times as the condition is true, so it depends on n.
Understanding how loops grow with input size helps you explain your code clearly and shows you know how programs behave as data grows.
"What if we changed the loop to stop when count < n/2? How would the time complexity change?"