0
0
Pythonprogramming~10 mins

__name__ and __main__ behavior in Python - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - __name__ and __main__ behavior
Python file starts
Set __name__ variable
Check if __name__ == "__main__"
Yes No
Run main code
Program ends
When a Python file runs, it sets __name__. If __name__ is "__main__", it runs the main code block; otherwise, it skips it.
Execution Sample
Python
def greet():
    print("Hello from greet()")

if __name__ == "__main__":
    greet()
This code runs greet() only if the file is run directly, not when imported.
Execution Table
Step__name__ valueCondition (__name__ == "__main__")ActionOutput
1"__main__"TrueCall greet()
2"__main__"TrueInside greet(): print messageHello from greet()
3"__main__"TrueEnd of program
💡 Program ends after running greet() because __name__ == "__main__" is True
Variable Tracker
VariableStartAfter Step 1After Step 2Final
__name__Set by Python"__main__""__main__""__main__"
Key Moments - 2 Insights
Why does the code inside if __name__ == "__main__" run only when the file is run directly?
Because when run directly, Python sets __name__ to "__main__" (see execution_table step 1). When imported, __name__ is the module name, so condition is False and code inside is skipped.
What happens if we import this file in another Python file?
The __name__ variable will be the module's name (not "__main__"), so the condition is False and greet() is not called automatically (see concept_flow No branch).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of __name__ at Step 1?
A"__main__"
B"greet"
C"module"
DUndefined
💡 Hint
Check the __name__ value column in execution_table row 1
At which step does the program print "Hello from greet()"?
AStep 1
BStep 2
CStep 3
DIt never prints
💡 Hint
Look at the Output column in execution_table row 2
If this file is imported, what happens to the condition __name__ == "__main__"?
AIt becomes True and runs greet()
BIt causes an error
CIt becomes False and skips greet()
DIt runs greet() twice
💡 Hint
Refer to key_moments explanation about import behavior
Concept Snapshot
Python sets __name__ to "__main__" when a file runs directly.
Use if __name__ == "__main__": to run code only when file is executed, not imported.
This helps separate reusable code from script code.
When imported, __name__ is the module name, so main code is skipped.
Full Transcript
When you run a Python file, Python sets a special variable called __name__ to "__main__". This means the file is the main program. If you import the file as a module, __name__ is set to the module's name instead. Using the condition if __name__ == "__main__": lets you write code that runs only when the file is run directly, not when imported. In the example, greet() runs only if the file is the main program. This helps keep code organized and reusable.