Learn Python Main Function with Examples: Understand __main__

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 (): 
  • Only "Guru99" prints out
  • and not the code "Hello World."
Learn Python Main Function with Examples: Understand __main__
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.
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"

Comments

  1. I'm just enjoying the tutorials, you make it so easy to understand for a.beginners like me.

    ReplyDelete
  2. I really liked your Information. Keep up the good work. Laravel Tutorials Online

    ReplyDelete
  3. wonderful blogs! thankyou for sharing a reliable information for us and who is looking for a particular courses if any one want to learn python core to advance contact us on 9311002620 and visit our further websites https://www.htsindia.com/Courses/python/python-training-institute-in-south-delhi

    ReplyDelete

Post a Comment

Popular posts from this blog

Introduction to BIG DATA: Types, Characteristics & Benefits

Hadoop Tutorial: Features, Components, Cluster & Topology