Python is an object-oriented programming language ideally designed for rapid prototyping of complex applications. Like Perl, Python source code is also available under the GNU General Public License (GPL).

In this article we will see about Python Main Function and will Understand __main__ with Examples

1) What does if __name__ == "__main__": do?

When the Python interpreter reads a source file, it executes all of the code found in it.

Before executing the code, it will define a few special variables. For example, if the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value "__main__". If this file is being imported from another module, __name__ will be set to the module's name.

Running module (the source file) as the main program means, executing the source file or module with python command as: python

After setting up the special variables, the interpretor will execute the import statement and load those modules (imported files).

That means '__name__ == "__main__":' will return false if written inside imported files and code indide the body of 'if' will not execute, and if the same condition is written in executing file( condition will return true and code inside the body will execute.

Lets assume we have two modules (.py source files), and
import example
if __name__ == "__main__":
	print 'I am main from pythonDemo!'
print 'I am called'

if __name__ == '__main__':
	print 'I am main from example!'

Output: Output will be something like this:

I am called
I am main from pythonDemo!

As the output shows, if __name__ == '__main__', condition is executed on only.

2) Define main() in python

Defining main() in python is not different than other functions, you have to call it as well to be used as main in other Java like programming language, but you will not want main of each source file to be called, so thy above condition as shown in point 1 whould be placed:
def main():
	print 'I am main from pythonDemo!'

if __name__ == "__main__":

Output: Output will be something like this:

I am main from pythonDemo!

In this article we have seen, Python Main Function and Understanding __main__ with Examples. In upcoming articles we will see more complex usecases and tricks of python.
  • By
  • Sep 30, 2017
  • Python