Interview Q&A / Python

BeginnerQuick answer1 min readUpdated 3 Oct 2026

What does if __name__ == "__main__" do in a Python script?

SHORT ANSWER

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

python
# greet.py
def hello(name):
    return f"Hello, {name}"

print("module name is", __name__)

if __name__ == "__main__":
    print(hello("Priya"))
bash
python greet.py
# module name is __main__
# Hello, Priya

python -c "import greet"
# module name is greet

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

#python#modules

Related questions

Practise more Python questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Python quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.