3

Can someone explain the flow of execution of a python program especially about the main function? It would be helpful if it is compared and contrasted with execution of C.

  • Hope [this](http://stackoverflow.com/questions/419163/what-does-if-name-main-do) helps – Rao Jan 10 '16 at 07:35

2 Answers2

1

when you execute "python myprog.py" the python interpeter will start running the script line by line:

import os #import the os module
print "prints somthing"
def f(num): ... # define a function

a = 5 / 2.0 # calculating stuff stuff ... 
if __name__ == '__main__': #__name__ is '__main__' only if this was the file that was started by the interpeter
    f(a) #calling the function f...

In C there is special function "main" that will be executed at startup. this (as explained above is NOT true for python)

Yoav Glazner
  • 7,936
  • 1
  • 19
  • 36
1

Without going in-depth, in c you have a specific "entry" function (main):

int main() {
    // stuff
}

This function is compiled and the executable will start with it.

In python you usually load a specific module (something like python mymodule.py) and verify main-ness by checking __name__'s value:

if "__main__" == __name__:
    print "this is main"

The __name__ variable is usually the module's name ("mymodule.py"), with an exception when it is the main module you've loaded (and then it is set to "__main__" automagically).

Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88