Home >Backend Development >Python Tutorial >What does 'if __name__ == __main__:' do?
The role of "if __name__ == __main__:": specifies the main method function. The main function is started when the script is executed, but will not be executed when other files are imported.
There are two ways to use a python file. The first is to execute it directly as a script, and the second is to be imported in the python script of other files. Call (module reuse) execution. Therefore, the function of if name == 'main': is to control the process of executing the code in these two situations. The code under if name == 'main': can only be executed in the first situation (that is, the file is directly executed as a script). will be executed, but importing it into other scripts will not be executed.
Example:
# file one.pydef func(): print("func() in one.py") print("top-level in one.py")if __name__ == "__main__": print("one.py is being run directly")else: print("one.py is being imported into another module")
# file two.pyimport one # start executing one.pyprint("top-level in two.py") one.func()if __name__ == "__main__": print("two.py is being run directly")else: print("two.py is being imported into another module")
When running python one.py, the output is:
top-level in one.py one.py is being run directly
When running python two.py, the output is:
top-level in one.py one.py is being imported into another module top-level in one.pyfunc() in one.py two.py is being run directly
The above is the detailed content of What does 'if __name__ == __main__:' do?. For more information, please follow other related articles on the PHP Chinese website!