All IT Courses 50% Off
Python Tutorials

Python’s main() Function with Examples

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

main function

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 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.

All IT Courses 50% Off
def main():
	print("I am main function")

if __name__ == "__main__":
Python's main() Function with Examples

We can call different functions from the main functions. Let’s have a look at the example.

main functions example

Understanding __name__ == “__main__”

Take a look at the screenshot below. When we run the file __main__ is set to “__name__”

def function_one():
	print("I am first function")

if __name__ == "__main__":
print("Value in built variable name is:  ", __name__)
understanding main

But when we import the file in secondFile __main__ is set to “articles”

This __main__ function gives us control over when to run the main function.

import articles
Python's main() Function with Examples

Facebook Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Back to top button