How to use the main function in Python

On this article, I’ve defined about learn how to use the principle operate within the python programming language.



essential operate

There’s a operate named essential which is taken into account the entry level of a program. It means, irrespective of what number of features we’ve got outlined in our program it can discover the principle operate and executes it on the very starting, and in a while different packages shall be executed serially which are inside the principle operate.

As python is an interpreted language, it doesn’t have any essential operate of any entry factors. It merely executes this system from the highest to backside strategy. Python offers a particular built-in variable named __name__ and on this article, we’ll discover how we will use the principle operate because the entry level of a python program and executes it on the very starting.

Let’s see the under instance first the place we don’t add any performance and easily outline a python operate and named it essential()

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

print ("Welcome")


# output: Welcome
Enter fullscreen mode

Exit fullscreen mode

Within the above program, we will see that it solely prints the Welcome within the output and doesn’t execute the principle operate. However we wish to execute the principle operate in our program. To carry out this motion we have to use the python’s built-in __name__ variable and set the variable worth as the principle operate. See the under code instance:

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

if __name__ == "__main__":
    essential()

print ("Welcome")


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

Exit fullscreen mode

This time the principle operate has been executed first after which the remainder of the code. The primary purpose behind is that we’ve got used python’s built-in variable and when the if block of code executes it has discovered the principle operate and easily returned true consequently, the principle operate has been executed.

Thanks for studying my article until finish. I hope you realized one thing particular as we speak. If you happen to loved this text then please share to your mates and if you already know another methods to make use of the principle operate in Python Programming Language or ideas to share with me then please write within the remark field.

Add a Comment

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