How to execute code only when the source file is run as the main program in Python

Executing code only when the source file is directly being run prevents certain code from being executed when it is being imported as a module. This allows a Python file to be used both as a script to be run, as well as a module to be imported into other files.

Solution for How to execute code only when the source file is run as the main program in Python : You can use the __name__ attribute to execute code only when the file is being run Write an if-statement to check whether the __name__ attribute is equal to “__main__”. A module’s __name__ is set to “__main__” whenever it is read from standard input, a script, or from an interactive prompt. Any code inside of the if-statement will not be run if the source file is imported into another file.


how-to-execute-code-only-when-the-source-file-is-run-as-the-main-program-in-python