Cheap Jerseys Cheap NFL Jerseys Cheap NFL Jerseys Cheap Football jerseys Cheap NFL Jerseys Wholesale Jerseys Cheap NHL Jerseys Cheap Jerseys From China Cheap MLB Jerseys Cheap Jerseys Cheap Jerseys Cheap Jerseys Wholesale Jerseys Python if __name__ == "__main__" Explanation - WTMatter

Python if __name__ == “__main__” Explanation

If Name == Main

Find out what is if __name__ == “__main__” in Python and its purpose. Learn about the __name__ attribute and when its value is set to “__main__”.

What is if __name__ == "__main__"?

You might have seen the following line of code in numerous python programs.

if __name__ == "__main__"

But what is its purpose? Let’s find out.

It is simply an if statement having the condition __name__ == "__main__"

The condition is to check if the attribute __name__ has the string type value "__main__".

__name__ Attribute and "__main__" value

Every module in python has some special attributes and __name__ is one of them. The value of this module is usually set to "__main__" or to contain the name of the current module.


Let’s understand this concept with the help of examples.

I’ve created a file named and written the following code into it.

Now, to execute the python code written in the file,, I used the following command.


And it printed the following output to the console.

The program is executed as the main program.
As you can see, the value of __name__ is __main__
That's why the control is inside the if statement body.
Calling demo() Function
This is a demo function of some_module.

This code was simple. As the value of the attribute __name__ matches with the value __main__, therefore, every single statement that was written inside the if block is executed and hence the function demo() is also being called.

Now we’ve created a new file named and inside this file, the following python code is written.

Now, clearly observe the output of the above code by running the file using the following command.


As you can see in the output, __name__ still has the value __main__ but we refer the __name__ attribute for some_module it gives the value some_module.

This is a demo function of some_module.

I hope now you have clear idea about the value of the __name__ attribute.

If it’s called within the module itself, it has the value __main__ while if it is called in some other module by the original module reference, its value is the name of the module itself.

Also, the if block code is now not executed as the value of the attribute __name__ is not anymore __main__.

I hope you found this guide useful. If so, do share it with others who are willing to learn Python. If you have any questions related to this article, feel free to ask us in the comments section.

And do not forget to subscribe to WTMatter!

Subscribe To WTMatter!

Receive updates of our latest articles via email. Enter your email address below to get started.

Leave a Reply

Your email address will not be published. Required fields are marked *