__name__ and __main__ behavior in Python - Time & Space Complexity
Let's explore how the time it takes to run a Python script changes when using the if __name__ == "__main__" check.
We want to see how running code inside this check affects the program's work as input grows.
Analyze the time complexity of the following code snippet.
def print_numbers(n):
for i in range(n):
print(i)
if __name__ == "__main__":
print_numbers(5)
This code prints numbers from 0 up to n-1 only when the script is run directly, not when imported.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop inside
print_numbersthat prints numbers. - How many times: It runs exactly
ntimes, wherenis the input number.
As the input n grows, the number of print operations grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: The work grows directly with the input size, so doubling input doubles work.
Time Complexity: O(n)
This means the program's running time grows in a straight line with the input size.
[X] Wrong: "The if __name__ == '__main__' check changes how many times the loop runs."
[OK] Correct: This check only controls if the code runs when the script is executed directly. It does not affect how many times the loop inside the function runs once called.
Understanding this behavior helps you explain how Python scripts run and how to control code execution, a useful skill for writing clear and efficient programs.
"What if we call print_numbers(n) outside the if __name__ == '__main__' block? How would the time complexity change when importing this script?"