Junior
210
Does Python have a main() function?
Answer from AI
sobes.tech AI
Python does not have a built-in main() function like C++ or Java. However, it is common practice to use the if __name__ == "__main__": construct to define the entry point of a program.
When a script is run directly, the special variable __name__ takes the value "__main__". If the script is imported as a module into another script, __name__ will be equal to the module's name.
This allows executing certain code only when the script is run directly, such as running main functions, parsing command-line arguments, etc.
# my_module.py
def some_function():
print("some_function executed")
if __name__ == "__main__":
# This code runs only when my_module.py is executed directly
print("Running script directly")
some_function()
# script.py
import my_module
print("Importing my_module")
# This code runs when script.py is executed
# When imported, the if __name__ == "__main__": block in my_module.py does not execute
my_module.some_function()
When running my_module.py, the output will be:
Running script directly
some_function executed
When running script.py, the output will be:
Importing my_module
some_function executed