0
0
Pythonprogramming~5 mins

Why variables are needed in Python - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why variables are needed
O(n)
Understanding Time Complexity

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?

Scenario Under Consideration

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

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.
How Execution Grows With Input

As the number of numbers to add grows, the steps grow in the same way.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: The work grows directly with how many numbers we add.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line as the input size grows.

Common Mistake

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

Interview Connect

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.

Self-Check

"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?"