PY0003 Python Main Function with Examples: Understand __main__
Posted by Superadmin on November 10 2018 05:57:07

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 "Guru99"

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 "Guru99". When you run the function def main (): 

Learn Python Main Function with Examples: Understand __main__

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

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

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.

Learn Python Main Function with Examples: Understand __main__

Note: Make sure that after defining a main function, you leave some indent and not declare the code right below the def main(): function otherwise it will give indent error.

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

print("Guru99")

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 "Guru99"

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

def main():
  print("Hello World!")
  
main()
print("Guru99")