Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 12, 2022 05:58 pm GMT

How to use the main function in Python Programming Language

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

main function

Theres a function named main which is considered the entry point of a program. It means, no matter how many functions we have defined in our program it will find the main function and executes it at the very beginning, and later on other programs will be executed serially that are inside the main function.

As python is an interpreted language, it does not have any main function of any entry points. It simply executes the program from the top to bottom approach. Python provides a special built-in variable named __name__ and in this article, we will explore how we can use the main function as the entry point of a python program and executes it at the very beginning.

Lets see the below example first where we do not add any functionality and simply define a python function and named it main()

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

In the above program, we can see that it only prints the Welcome in the output and does not execute the main function. But we want to execute the main function in our program. To perform this action we need to use the pythons built-in __name__ variable and set the variable value as the main function. See the below code example:

def main():     print ("Welcome to KCD Chennai!")if __name__ == "__main__":    main()print ("Welcome")# Output: # Welcome to KCD Chennai!# Welcome

This time the main function has been executed first and then the rest of the code. The main reason behind is that we have used pythons built-in variable and when the if block of code executes it has found the main function and simply returned true as a result, the main function has been executed.

Thanks for reading my article till end. I hope you learned something special today. If you enjoyed this article then please share to your friends and if you know any other ways to use the main function in Python Programming Language or thoughts to share with me then please write in the comment box.


Original Link: https://dev.to/kcdchennai/how-to-use-the-main-function-in-python-programming-language-56im

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To