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.

1
  • Hope this helps Commented Jan 10, 2016 at 7:35

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

Comments

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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.