What does if __name__ == '__main__': do in Python ?

preview_player
Показать описание
The if __name__ == "__main__": statement in Python is a conditional statement that checks whether the current script is being run as the main program or being imported as a module into another script.

When a Python module is imported into another script, all of the code in that module is executed, including any code that is outside of functions or classes. This can sometimes lead to unintended behavior, especially if the imported module has code that is meant to be executed only when the module is run as the main program.

To avoid this issue, the if __name__ == "__main__": statement is used to enclose the code that should only be executed when the module is run as the main program. When the Python interpreter runs a script, it sets the special variable __name__ to the string "__main__" for the main module. If the module is being imported as a module into another script, __name__ is set to the module's name.

By using the if __name__ == "__main__": statement to enclose code that should only be executed when the module is run as the main program, you can prevent that code from being executed when the module is imported as a module into another script.

Here's an example of how this statement can be used:

python
Copy code
# Example Python module
def my_function():
print("This is my function.")

if __name__ == "__main__":
# This code will only be executed when the module is run as the main program
print("This is the main program.")
my_function()
In this example, the my_function() function is defined outside of the if __name__ == "__main__": statement, so it will be executed whether the module is run as the main program or imported as a module. The print() statement and the call to my_function() are enclosed in the if __name__ == "__main__": statement, so they will only be executed when the module is run as the main program.
Рекомендации по теме