What is the main function?
The first function which is called when you run a program in any programming language is the main function. Python specifically does not have the Python’s main function as it is an interpreter language but we can create the main function and run it when the python file is run using special variable __name__. Let us first see what is __name__
__name__ is a special variable
Python automatically makes __name__ = “__main__” as you can see below
So we will write a condition to check whether __name__ == __main__ then call the Python’s main function. This checking will make sure that this hello.py is running this script. We will take a deep look into this when we will discuss importing other files than you will be able to see the importance of this.
def main():
print("I am main function")
if __name__ == "__main__":
main()
We can call different functions from the main functions. Let’s have a look at the example.
Understanding __name__ == “__main__”
Take a look at the screenshot below. When we run the articles.py file __main__ is set to “__name__”
def function_one():
print("I am first function")
if __name__ == "__main__":
function_one()
print("Value in built variable name is: ", __name__)
But when we import the articles.py file in secondFile __main__ is set to “articles”
This __main__ function gives us control over when to run the main function.
import articles
print("Hello")