Knowpapa.com - a developer's blog

‘if __name__ == “__main__” | Python Coding Basics

Use of:

if __name__ == "__main__":

in any python program enables the use of the same file either as an independent program or as a imported module within another piece of code.

For example:

if __name__ == "__main__":
    print "i am running as an independent program"
else:
    print "i am running as an imported module"

When u run this code as a stand-alone program you will get

>>> i am running as an independent program

Now, save this file as test.py and type

>>> import test

The same program will give an output:
>>> i am running as an imported module

P.S: The terms “__name__” & “__main__” have double underscores on each side.
If you use _name_ or _maim_ (with single underscore) – you will get the error message:

if _name_ == “_main_”:
NameError: name ‘_name_’ is not defined

I had a hard time figuring this out :)