Python "if __name__ == ‘__main__’: ”means

module

Python code can be saved as a script file and reused by other programs. That file is called a module. By using "import" to load your own module using import, you can use the functions and classes defined in that module in other programs.

ʻIf name == ‘main’: `means

Create the following program for the time being

test.py


def test():
    print('Hello World!')
    
if __name__ == '__main__':
    test()
    
print('Module name:{}'.format(__name__))  #Display the name of the executed module

output


Hello World!

Why it is executed

Why is the variable " __name__ "executed even though I haven't declared it?

__name__ is created automatically when you load a Python script on a Python printer.

When you run a Python script directly, the script file will be recognized as a module named "\ _ \ _ main \ _ \ _" </ font> Therefore, if you execute the script file directly, the value '__ main__' will be automatically assigned to the __name__ variable.

in short

"if \ _ \ _ name \ _ \ _ =='\ _ \ _ main \ _ \ _':" means "execute only when executed directly, otherwise Does not run "</ font>

Try running it in the interpreter ʻIf name =='main':` becomes False and is not executed

>>> import test.py
Module name: test

Reference site

http://programming-study.com/technology/python-if-main/

Recommended Posts