DEV Community

MakendranG for Kubernetes Community Days Chennai

Posted on • Updated on

Main function in Python

In this article, I have explained about how to use the main function in the python programming language.

main function

The main function is considered the entry point of a program. It means that no matter how many functions we have defined in our program, it will find the main function and execute it at the very beginning, and later on other programs will execute it inside the main function.

Python does not have a main function in entry points. The program is executed from top to bottom. Python provides a special built-in variable named __name__. In this article, we will explore how we can use the main function as the entry point of a python program and execute it at the very beginning.

In the below example, we simply define a python function and call it main().

def main():
     print ("Welcome to KCD Chennai!")

print ("Welcome")


# output: Welcome
Enter fullscreen mode Exit fullscreen mode

In the above program, we can see that it only prints the Welcome and does not execute the main function. The main function of our program is to execute. To perform this action, we need to use the python's built-in variable __name__ and set it as the main function.

The code example is below:

def main():
     print ("Welcome to KCD Chennai!")

if __name__ == "__main__":
    main()

print ("Welcome")


# Output: 
# Welcome to KCD Chennai!
# Welcome
Enter fullscreen mode Exit fullscreen mode

The main function has been executed first, followed by the rest of the code. The main reason is that we have used python's built-in variable and when the block of code executes it finds the main function and returns true as a result, the main function has been executed.

Gratitude for perusing my article till end. I hope you realized some thing one-of-a-kind today. If you enjoyed this article then please share to your friends and if you comprehend any different approaches to use the main function in Python Programming Language or thoughts to share with me then please write in the comment box.

Oldest comments (0)