When you run a Python program, have you ever wondered where it actually starts? Unlike languages like C or Java that have a fixed main() function as the starting point, Python uses a special built-in variable called __main__ to figure out whether a file is being run directly or imported.
Let’s break it down in a beginner-friendly way.
1. What is __main__?
In Python, every file you write is called a module.
- If you run the file directly, Python assigns the name
"__main__"to that file. - If you import the file into another script, Python uses the file’s actual module name instead.
This way, Python knows whether your code should execute immediately or just sit ready to be reused.
2. A Simple Example
File: hello.py
print("This will always run")
if __name__ == "__main__":
print("This runs only when the file is executed directly")
Case 1: Run directly
python hello.py
Output:
This will always run
This runs only when the file is executed directly
Case 2: Import into another file
import hello
Output:
This will always run
Notice how the second line does not run when imported? That’s the power of if __name__ == "__main__":.
3. Do You Need a Function Called main()?
No! Python doesn’t automatically call a function named main().
That’s just a convention programmers use to organize code.
You can call your starting function whatever you like:
def app():
print("Hello from app!")
if __name__ == "__main__":
app()
Here, app() is your program’s entry point — and it works just as well as main().
4. Why is This Useful?
The __main__ check helps you:
- Keep code reusable → Functions and classes can be imported without running extra code.
- Control program flow → Only the code you decide runs when the file is executed.
Think of it like saying:
➡️ “Run this part only if I am the boss (the main file). Ignore it if I’m just a helper (an imported module).”
5. Best Practice
It’s good style to wrap your script’s main logic inside a function — named main(), app(), or anything else you like — and call it inside the __main__ check:
def run():
print("Hello from run()")
if __name__ == "__main__":
run()
This makes your code cleaner, more testable, and easier to reuse.
6. Quick Recap
- Python uses the variable
__name__to decide what to run. - If the file is run directly →
__name__ = "__main__". - If imported →
__name__ = "<module_name>". - You can call your entry function anything (e.g.,
main(),app(),run()). - The only fixed part is the condition:
if __name__ == "__main__":
✅ Next time you see if __name__ == "__main__": in Python code, remember: it’s not about a fi