__name__ and __main__ behavior in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
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?"
Practice
__name__ contain when a Python file is run directly?Solution
Step 1: Understand the role of
When a Python file runs directly,__name____name__is set to the string "__main__".Step 2: Differentiate direct run vs import
If the file is imported,__name__is the module's name, not "__main__".Final Answer:
"__main__" -> Option CQuick Check:
__name__= "__main__" when run directly [OK]
- Thinking __name__ holds file path
- Confusing __name__ with Python version
- Assuming __name__ is always module name
Solution
Step 1: Check correct variable and string
The variable is__name__and the string to compare is "__main__".Step 2: Verify syntax correctness
Use double equals==for comparison, and colons to start the block.Final Answer:
if __name__ == '__main__': -> Option AQuick Check:
Correct syntax uses==and exact names [OK]
- Using single equals (=) instead of double (==)
- Swapping __name__ and __main__
- Missing colon at end of if statement
def greet():
print('Hello!')
if __name__ == '__main__':
greet()Solution
Step 1: Check if condition when run directly
Since the file runs directly,__name__ == '__main__'is True, sogreet()is called.Step 2: Understand greet() function output
The function prints "Hello!" once.Final Answer:
Hello! -> Option DQuick Check:
Function called once prints "Hello!" [OK]
- Thinking greet() runs twice
- Assuming no output without main guard
- Confusing function call with definition
def main():
print('Running main')
if __name__ = '__main__':
main()Solution
Step 1: Check the if condition syntax
The condition uses single equals (=) which is assignment, not comparison, causing SyntaxError.Step 2: Confirm function and indentation
The functionmain()is defined correctly and indentation is fine.Final Answer:
SyntaxError due to single equals (=) in if condition -> Option BQuick Check:
Use == for comparison, not = [OK]
- Using = instead of ==
- Assuming function undefined error
- Ignoring indentation correctness
# file1.py
def greet():
print('Hi from file1')
if __name__ == '__main__':
greet()
# file2.py
import file1
print('In file2')What will be the output when you run
file2.py?Solution
Step 1: Understand import behavior with __name__
Whenfile1is imported, its__name__is "file1", not "__main__", sogreet()inside the if block does NOT run.Step 2: Check what runs in file2.py
Onlyprint('In file2')runs, so output is just "In file2".Final Answer:
In file2 -> Option AQuick Check:
Import skips main block, prints only file2 message [OK]
- Assuming greet() runs on import
- Expecting both prints always
- Confusing __name__ values on import
