Hi Alex, On 14 June 2012 23:18, Alexander Quest <alexxqu...@gmail.com> wrote: > if __name__ == '__main__': > main() > > This calls the main function, but I don't understand what the 'if' statement > is doing here. In the simple programs that I've seen this so far, there is > no variable called "_name_", and even if there was, why is it comparing it > to "_main_"? Why can't the main function just be called by typing main()- > why do we need this if statement to precede it? Thanks.
In short, consider the implications of the fact that your file, apart from being a program that can run standalone, might also be a Python module that might be used in another program. Oftentimes you want to write your Python code in such a way that when the module is run directly you want it to do something useful (such as run a main() function, e.g. maybe run some unit/self-tests or whatever), while when you import it for use in another program/module then you probably rather do *not* want it to run as if it is itself the "main program". So, in order to differentiate the 2 cases, there exists the above Python idiom. So, when a module is directly run as the "main program", then the name of the module being run, which is reflected by the variable __name__, made available by the Python interpreter, will be equal to "__main__", while when it's imported it will be equal to the module name. This allows your module to know when it's running whether it's running as the main program or just running because it's been imported by another module. Does that answer your question? Walter _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor