Understanding if __name__ == '__main__' in Python
This is one of the most confusing Python lines for beginners — but don't worry, we'll break it down with real examples and make it crystal clear!
What does if __name__ == "__main__" mean?
Imagine you're writing a Python file — maybe a fun game or a simple calculator. Now ask yourself: should this file run some code only when it's opened directly? Or stay quiet if someone else imports it into their own project?
That's exactly what this line does. It's Python's way of saying: "Run this part only when the file is executed directly — not when it's imported."
It checks a built-in variable called __name__. If you run the file directly with python filename.py, then __name__ becomes "__main__". But if someone imports your file into another script, __name__ becomes the name of your file instead.
So why should you care?
This small line is super useful when:
- You're writing utility functions that others might import.
- You want to test your code with print statements or small examples.
- You're building Python scripts and want better control of when things happen.
Let's See It in Action
Here's a simple example — run this file directly and it prints a greeting:
def say_hello():
print("Hello, world!")
if __name__ == "__main__":
say_hello()
If you run greet.py directly, it prints Hello, world!. But if you import it from another file:
import greet
Nothing happens. The code inside the if __name__ == "__main__" block is silently skipped when the file is imported. This keeps your code clean and prevents unwanted side effects when using modules.
__name__ == "__main__" is True only when you run the file directly. It's False when the file is imported by another script.
Common Mistakes
- Using
=instead of==:if __name__ = "__main__"is a syntax error. Always use==for comparison. - Indentation errors: The code inside the
ifblock must be properly indented — 4 spaces in. - Expecting it to run on import: Code inside this block won't run when the file is imported. That's the whole point!
- Forgetting the underscores: It must be
__name__and"__main__"— double underscores on both sides.
Wrap Up
So now you know what if __name__ == "__main__" means! It's not as scary as it looked. Think of it as a way to tell Python: "Only run this part when I'm executing the file directly."
This little line becomes really powerful when your projects grow or when you're sharing code with others. Keep practicing, and you'll start using it without even thinking about it!
= vs == in Python · Coding roadmap from scratch · Learn coding without a CS degree?
Hope this cleared your doubt! More coming soon — keep learning with Kiddo 🎉