Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

The function and usage of if name = & quot;main" in python

Shulou Source: shulou.com Published: 2022-06-03 07:27:12 09月23日 Update

Today, the editor will bring you an article introducing the function and usage of if name = = "main" in python. The editor thinks it is very practical, so I will share it for you as a reference. Let's follow the editor and have a look.

The role of if name = = 'main':

Generally speaking, the code after this statement cannot be executed when the script is referenced.

A python file is usually used in two ways: first, it is executed directly as a script, and second, import is called into other python scripts (module reuse) to execute. Therefore, the function of if name = = 'main': is to control the process of code execution in both cases. The code after the if name = =' main': line is executed only in the first case (that is, the file is executed directly as a script), while import is not executed in other scripts.

Test.py

Print ("this is the first part")

If name = = "main":

Print ("this is part two")

Run the test.py script directly

PY, the result is

This is the first part.

This is the second part.

Test.py is introduced into another script (import_test.py)

Import_test.py

Import test

Running result

This is the first part.

Each python module (python file, that is, test.py and import_test.py here) contains the built-in variable name, and when the module is executed directly, name equals the file name (including the suffix .py); if the module import into other modules, the module's name is equal to the module name (excluding the suffix .py).

"main" always refers to the name of the currently executing module (including the suffix .py). Then when the module is executed directly, the name = = 'main' result is true.

When import_test.py is running

The name value is test

The mainvalue is import_test.py

The result of if is false, and the statement following the line of if statement is not executed

"description: the source code here does not consider indentation."

The above is an introduction to the function and usage of if name = = "main" in python. The code example is simple and straightforward, if you encounter this problem in your daily work. Through this article, I hope you can get something. For more details, please follow the industry information channel!

Tags: Module script this is function code file result suffix that is part one statement run name case part two practical popular and for this that is the method of use. Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Shulou Information Huawei Microsoft Apple