Why variables are needed in Python - Performance Analysis
We want to see how the use of variables affects the steps a program takes as it runs.
How does storing and reusing values with variables change the work done?
Analyze the time complexity of the following code snippet.
result = 0
for i in range(1, 101):
result += i
print(result)
This code adds numbers from 1 to 100 using a variable to keep the running total.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding numbers inside the loop.
- How many times: 100 times, once for each number from 1 to 100.
As the number of numbers to add grows, the steps grow in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with how many numbers we add.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the input size grows.
[X] Wrong: "Using a variable makes the program faster by reducing the number of steps."
[OK] Correct: Variables store values but do not reduce the number of times the loop runs, so the main work still depends on input size.
Understanding how variables hold data and how loops repeat work helps you explain how programs grow with input size, a key skill in coding interviews.
"What if we replaced the variable with a function call inside the loop that calculates the sum each time? How would the time complexity change?"