0
0
Pythonprogramming~5 mins

Function call and execution flow in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Function call and execution flow
O(n)
Understanding Time Complexity

When we call a function, the computer runs the code inside it. We want to know how the time it takes changes as the input grows.

How does the number of steps grow when the function runs with bigger inputs?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

def print_numbers(n):
    for i in range(n):
        print(i)

print_numbers(5)

This function prints numbers from 0 up to n-1. It runs a loop that repeats n times.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that prints each number.
  • How many times: It runs exactly n times, once for each number from 0 to n-1.
How Execution Grows With Input

As n gets bigger, the loop runs more times, so the total steps grow in a straight line with n.

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

Pattern observation: Doubling n doubles the work because each number is printed once.

Final Time Complexity

Time Complexity: O(n)

This means the time grows in direct proportion to the input size n.

Common Mistake

[X] Wrong: "The function runs in constant time because it just calls print."

[OK] Correct: The print happens inside a loop that runs n times, so the total time depends on n, not just one step.

Interview Connect

Understanding how function calls and loops affect time helps you explain your code clearly and shows you know how programs grow with input size.

Self-Check

"What if we added another loop inside the function that also runs n times? How would the time complexity change?"