When should the statement if __name__==’__main__’ be used?

Kalpana P
2 min readNov 4, 2024

--

In Python, both scripts and modules are common ways of organizing and running code, but they have different purposes and are used in different contexts.

A Python script is a file containing code intended to be executed directly either by using the Run | Run module (IDE) or from the command line using “python my_script_demo.py” as a standalone program. The if __ name __ == '__ main __' statement in Python checks if the current script is being run directly as the main program, or if it’s being imported as a module into another program. Also, it can be included in the script to prevent certain code from running if the script is imported as a module.

A Python module is a file that contains functions, classes, and variables that can be imported and reused in other scripts or programs. In this scenario, the statement, the statement if __name__ == “__main__” need not be included since this is not meant to be executed directly. Even if we are including the statement, will return false and work accordingly.

Example

Cube of a given number

If we execute the above code as a standalone code using the Run | Run Module, the output is

= RESTART: C:/Users/admin/AppData/Local/Programs/Python/Python311/article_1.py

__main__

Enter n 10

cube of 10 is 1000

Explanation: As the __name__ contains __main__, the condition remains true, which invokes the main method, which in turn calls the cube(), which returns the cube of the given value.

If the above is imported, the __name__ variable contains the actual module name. NOTE: module name is actually, the name of the Python file.

Example

>>>import math_demo

math_demo #output of print(__name__)

The above will not invoke the main() method, because the __name__ contains math_demo (module name).

>>>math_demo.main() #invokes the main method, which provides the following output

Enter n 10

cube of 10 is 1000

CONCLUSION: In a nutshell, all Python scripts are modules, but not all modules are scripts. A script is meant to be executed, while a module is meant to be imported.

--

--

Kalpana P
Kalpana P

Written by Kalpana P

Working as an Assistant Professor in the Department of Computer Science, CHRIST(Deemed to be University), Bangalore.

No responses yet