Python Main Function : Understand __main__

Python Main function is the entry point of any program. But python interpreter executes the source file code sequentially and doesn’t call any method if it’s not part of the code. But if it’s directly part of the code then it will be executed when the file is imported as a module.

Before we jump more into Python coding, we get familiarize with Python Main function and its importance.

Consider the following code:

def main():
     print "hello world!"
     print "SolutionSaid"

Checkout how to run your first python Programme :

Here we got two pieces of print one is defined within a main function that is “Hello World” and the other is independent which is “SolutionSaid”. When you run the function def main ():

  • Only “SolutionSaid” prints out
  • and not the code “Hello World.”
def main(): 
       print ("hello world!") 
       print ("SolutionSaid")

It is because we did not declare the call function “if__name__== “__main__”.

  • When Python interpreter reads a source file, it will execute all the code found in it.
  • When Python runs the “source file” as the main program, it sets the special variable (__name__) to have a value (“__main__”).
  • When you execute the main function, it will then read the “if” statement and checks whether __name__ does equal to __main__.
  • In Python “if__name__== “__main__” allows you to run the Python files either as reusable modules or standalone programs.

Like C, Python uses == for comparison while = for assignment. Python interpreter uses the main function in two ways:-

  • import: __name__= module’s filename

    if statement==false, and the script in __main__ will not be executed

  • direct run:__name__=__main__

    if statement == True, and the script in _main_will be executed

  • So when the code is executed, it will check for module name with “if.”

It is important that after defining the main function, you call the code by if__name__== “__main__” and then run the code, only then you will get the output “hello world!” in the programming console as shown below.

 

def main(): 
       print ("hello world!") 
     if __name__ =="__main__":
       main()
       print ("SolutionSaid")

Above examples are Python 3 codes, if you want to use Python 2, please consider following code

def main():
  print "Hello World!"
  
if __name__== "__main__":
  main()

print "SolutionSaid"

In Python 3, you do not need to use if__name. Following code also works

def main():
  print("Hello World!")
  
main()
print("SolutionSaid")
Python Main Function : Understand __main__

Leave a Reply

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

Scroll to top