Function call and execution flow in Python - Time & Space 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?
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 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.
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 |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: Doubling n doubles the work because each number is printed once.
Time Complexity: O(n)
This means the time grows in direct proportion to the input size n.
[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.
Understanding how function calls and loops affect time helps you explain your code clearly and shows you know how programs grow with input size.
"What if we added another loop inside the function that also runs n times? How would the time complexity change?"