0
0
Pythonprogramming~5 mins

__name__ and __main__ behavior in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: __name__ and __main__ behavior
O(n)
Understanding Time 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.

Scenario Under Consideration

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

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop inside print_numbers that prints numbers.
  • How many times: It runs exactly n times, where n is the input number.
How Execution Grows With Input

As the input n grows, the number of print operations grows the same way.

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

Pattern observation: The work grows directly with the input size, so doubling input doubles work.

Final Time Complexity

Time Complexity: O(n)

This means the program's running time grows in a straight line with the input size.

Common Mistake

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

Interview Connect

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.

Self-Check

"What if we call print_numbers(n) outside the if __name__ == '__main__' block? How would the time complexity change when importing this script?"