What is if __name__ == “__main__” ??

Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

Every module in python has a special attribute called __name__ . The value of __name__  attribute is set to '__main__'  when module run as main program. Otherwise the value of __name__  is set to contain the name of the module.

Consider the following code for better understanding.

Here we have defined a new module my_module . We can execute this module as main program by entering the following code

Expected Output:

here we are creating a new module and executing it as main program so the value of __name__ is set to '__main__' . As a result if condition satisfies and hello()  function gets called.
Now create a new file called using_module.py  and write the following code

Expected Output:

As you can see now if statement in my_module  fails to execute because the value of __name__  is set to 'my_module' .

Other Tutorials

This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

Leave a Reply

8 Comments on "What is if __name__ == “__main__” ??"

Notify of
Sort by:   newest | oldest | most voted

[…] *args and **kwargs What is if __name__ ==”__main__”?? […]

Shakti Das

Nice Explanation bro i was searching from last 1 wk .but after reading your explanation my search stops hear.you are the python destiny.


Thanks so much, the best explanation i found on web !

Khanh N

The best explanation on this topic out of the ones I’ve been reading. Thank you!


thanks a lot. It’s very concise and clear 🙂


best and easy explanation of __name__



Rohit Gupta

thanks for the explanation