In Python there is nothing special about the name
main
. We could have called this function anything we wanted. We chose main
just to be consistent with some of the other languages.
Before the Python interpreter executes your program, it defines a few special variables. One of those variables is called __name__ and it is automatically set to the string value "__main__" when the program is being executed by itself in a standalone fashion. On the other hand, if the program is being imported by another program, then the __name__ variable is set to the name of that module. This means that we can know whether the program is being run by itself or whether it is being used by another program and based on that observation, we may or may not choose to execute some of the code that we have written.
For example, assume that we have written a collection of functions to do some simple math. We can include a main function to invoke these math functions. It is much more likely, however, that these functions will be imported by another program for some other purpose. In that case, we would not want to execute our main function.
def squareit(n): return n * n def cubeit(n): return n*n*n def main(): anum = int(input("Please enter a number")) print(squareit(anum)) print(cubeit(anum)) if __name__ == "__main__": main()
沒有留言:
張貼留言