Reputation: 35
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.
Upvotes: 3
Views: 254
Reputation: 31339
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).
Upvotes: 1
Reputation: 8066
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)
Upvotes: 1