What does if __name__ == "__main__" do in a Python script?
When a file runs directly, Python sets its __name__ to "__main__". When it is imported, __name__ is the module's name instead. The if-check lets a file run some code only when executed as a script, not when imported.
Explain it simply
A file can play two roles: a toolbox that others borrow from, or a program you run. The check asks "am I being run directly, or just borrowed?" so the file only starts the main program in the first case, and importing it stays harmless.
Example
# greet.py
def hello(name):
return f"Hello, {name}"
print("module name is", __name__)
if __name__ == "__main__":
print(hello("Priya"))python greet.py
# module name is __main__
# Hello, Priya
python -c "import greet"
# module name is greetWhen imported, the function hello is available but the greeting is not printed. Without the guard, every import would run the demo code.
What to say in the interview
"__name__ is '__main__' when a file is executed directly and the module name when imported. The guard lets me keep reusable functions and a runnable entry point in one file, and it prevents side effects at import time. It is also essential for multiprocessing on Windows and macOS, which re-import the main module."
Common mistakes
- Putting heavy work at module top level instead of inside a function called from the guard.