In Chapter 2, Writing Your First Modular Program, we saw your system's main program is often named
main.py and typically has the following structure:
def main(): ... if __name__ == "__main__": main()
__name__ global variable will be set to the value
"__main__" by the Python interpreter when the user runs your program. This has the effect of calling your
main() function when the program is run.
There is nothing special about the
main.py program, however; it's just another Python source file. You can take advantage of this to make your Python modules executable from the command line.
Consider, for example, the following module, which we will call
def double(n): return n * 2 if __name__ == "__main__": print("double(3) =", double(3))
This module defines some functionality, in this case a function named
double(), and then uses the
if __name__ == "__main__" trick to demonstrate and test the module's functionality when it is run from...