If you’ve been learning Python, you’ve probably seen this mysterious line at the bottom of many scripts:
if __name__ == "__main__":
At first, it looks confusing — like some kind of secret spell every Python programmer knows. But once you understand it, you’ll see it’s one of the most useful features of Python.
🔹 The Magic of __name__
Every Python file has a built-in variable called __name__
.
- When you run the file directly, Python sets
__name__ = "__main__"
. - When you import the file as a module, Python sets
__name__ = "filename"
.
This small difference decides whether certain code runs or stays quiet.
🔹 Why We Use It
That if __name__ == "__main__":
line is basically a safety gate.
It tells Python:
“Only run this block of code if the file is executed directly — not when it’s imported into another script.”
This makes the file act like a dual-purpose tool:
- Standalone Script – It runs fully when you execute it.
- Reusable Module – It stays quiet when imported, until you call specific functions.
Example
# myscript.py
def greet():
print("Hello from myscript!")
if __name__ == "__main__":
greet()
Case 1: Run directly
python myscript.py
Output: Hello from myscript!
Case 2: Import into another script
import myscript
myscript.greet()
It only runs when you call greet()
. Nothing extra happens automatically.
Real-Life Analogy 🎬
Think of it like a movie actor:
- Sometimes they’re the main character in their own movie (run directly).
- Other times, they make a cameo appearance in someone else’s movie (imported).
The if __name__ == "__main__":
line tells Python which role to play.
Why It Matters
✅ Keeps your code organized
✅ Avoids unwanted execution when imported
✅ Makes your script flexible: both a tool and a library
Key Takeaway
Next time you see:
if __name__ == "__main__":
remember — it’s not just a weird Python thing.
It’s the entry point of your script, deciding whether your code is the main star 🌟 or just a supporting role.