Does Python has a main function?

Subscribe to my newsletter and never miss my upcoming articles

What is the main method?

If you're familiar with languages like C, C++ etc you may have noticed the fact that we must need to use the main() method in your code. As those languages use the compiler(compiles all code at once) to run the code, it needs an entry point to start the compilation. But Python uses an interpreter(compiles code line by line), which means it doesn't need an entry point it'll simply start compilation from line 1. So, Python doesn't have a main function . But it has a concept called main modules.

The __name__ variable in Python

The __name__ is a special predefined variable in Python which stores the name of the current module.


Consider the following code in a file,


This code outputs,


Python by default stores the value of __name__ variable as __main__ (which indicates that this is the main module )

Now, consider the below code in a file,

import file1

I imported file1 here and printed the __name__ Now, the above code outputs,


What's the point here?

As you saw above, doesn't have any imported code. That's why the __name__ variable has a value of __main__ which means it is the main module but in we have imported the into Then the interpreter changes the __name__ variable to the imported module name in our case its file1.

if the module doesn't have any imports, then it will be the main module.

Now if you want to do certain things only in the main module not in the imported code, you can do like below.

def show ():
   print("Hello world")

# Only call the show method in main module 
if __name__ == "__main__" :

There's no actual reason to use this above process. Its just a feature :)

Comments (2)

Torikus's photo

It's very helpful.