Python Programming (16 Blogs) Become a Certified Professional
AWS Global Infrastructure

Data Science

Topics Covered
  • Business Analytics with R (16 Blogs)
  • Data Science (16 Blogs)
  • Mastering Python (16 Blogs)
  • Decision Tree Modeling Using R (1 Blogs)
SEE MORE

What is the Main Function in Python and how to use it?

275 Views
2 / 12 Blog from Python Fundamentals

Become a Certified Professional

Python is one of the most popular programming languages to learn. The main function in Python acts as the point of execution for any program. Defining the main function in Python programming is a necessity to start the execution of the program as it gets executed only when the program is run directly and not executed when imported as a module.

To understand more about python main function, let’s have a look at the topics that I will be covering in this article:

Let’s get started.

What are Python functions?

A function is a block of reusable code that forms the foundation of performing actions in a programming language. They are leveraged to perform computations on the input data and present the output to the end user.

We have already learned that a function is a piece of code written to perform a specific task. There are three types of functions in Python namely Built-in function, user-defined functions, and anonymous functions. Now, the main function is like any other function in Python.

So let’s understand what exactly is the main function in Python.

Main Function in Python

In most programming languages, there is a special function which is executed automatically every time the program is run. This is nothing but the main function, or main() as it is usually denoted. It essentially serves as a starting point for the execution of a program.

In Python, it is not necessary to define the main function every time you write a program. This is because the Python interpreter executes from the top of the file unless a specific function is defined. Hence, having a defined starting point for the execution of your Python program is useful to better understand how your program works.

A Basic Python main()

In most Python programs/scripts, you might see a function definition, followed by a conditional statement that looks like the example shown below:

def main():
    print("Hello, World!")
    if __name__== "__main__" :
main()

In the above example, you can see, there is a function called ‘main()’. This is followed by a conditional ‘if’ statement that checks the value of __name__, and compares it to the string “__main__“. On evaluation to True, it executes main().

And on execution, it prints “Hello, World!”.

This kind of code pattern is very common when you are dealing with files that are to be executed as Python scripts, and/or to be imported in other modules.

Let’s understand how this code executes. Before that, it’s very necessary to understand that the Python interpreter sets __name__ depending on the way how the code is executed. So, let’s learn about the execution modes in Python

Python Execution Modes

There are two main ways by which you can tell the Python interpreter to execute the code:

  • The most common way is to execute the file as a Python Script.
  • By importing the necessary code from one Python file to another.

Whatever the mode of execution you choose, Python defines a special variable called __name__, that contains a string. And as I said before, the value of this string depends on how the code is being executed.

Sometimes, when you are importing from a module, you would like to know whether a particular module’s function is being used as an import, or if you are just using the original .py (Python script) file of that module.

To help with this, Python has a special built-in variable, called __name__. This variable gets assigned the string “__main__” depending on how you are running or executing the script.

So, if you are running the script directly, Python is going to assign “__main__” to __name__, i.e., __name__= “__main__”. (This happens in the background).

As a result, you end up writing the conditional if statement as follows:

if __name__ == "__main__" :
		Logic Statements

Hence, if the conditional statement evaluates to True, it means, the .py (Python Script) file is being run or executed directly.

It is important to understand that, if you are running something directly on the Python shell or terminal, this conditional statement, by default, happens to be True.

As a result, programmers write all the necessary functional definitions on the top, and finally write this statement at the end, to organize the code.

In short, __name__ variable helps you to check if the file is being run directly or if it has been imported.

There are a few things you should keep in mind while writing programs that are going to have the main function. I have listed them in four simple steps. You can consider this as a good nomenclature to follow while writing Python programs that have the main function in them.

  • Use functions and classes wherever possible.

We have been learning the concepts of Object Oriented Programming and their advantages for a long time. It is absolutely necessary to place bulk logic codes in compact functions or classes. Why? For better code reusability, better understanding and for overall code optimization. In this way, you can control the execution of the code, rather than letting the Python interpreter execute it as soon as it imports the module.

Let us see the following piece of code:

def get_got():
print("…Fetching GOT Data… n")
data="Bran Stark wins the Iron Throne. n"
print("…GOT Data has been fetched…n")
return data

print("n Demo: Using Functions n")
got=get_got()
print(got)

In the above example, I’ve defined a function called “get_got“, which returns the string stored in the variable “data”. This is then stored in the variable called “got” which is then printed. I have written down the output below:

program2-Understanding main function in python 3-Edureka

  • Use __name__ to control the execution of your code.

Now you know what __name__ variable is, how and why it is used. Let us look at the code snippet below:

Now you know what __name__ variable is, how and why it is used. Let us look at the code snippet below:

if __name__ == "__main__":
			got = "Game of Thrones is a legendary shown"
			print(got)
			new_got = str.split(got)
			print(new_got)

In the above example, the conditional if statement is going to compare the values of the variable __name__ with the string “__main__“. If, and only if it evaluates to True, the next set of logical statements are executed. Since we are directly running the program, we know that the conditional statement is going to be True. Therefore, the statements are executed, and we get the desired output. In this way, we can use the __name__ variable to control the execution of your code. You may refer to the output displayed below:

program6-Understanding main function in python 3-Edureka

  • Create a function main() which has the code to be run.

By now, you know the various ways how a Python code can be executed. You also know why and when a main() function is used. It is time to apply it. Look at the following piece of code:

print("n Main Function Demo n")
	def demo(got):
		print("…Beginning Game Of Thrones…n")
		new_got = str.split(got)
		print("…Game of Thrones has finished…n")
		return new_got
	def main():
		got= "n Bran Stark wins the Iron Throne n"
		print(got)
		new_got = demo(got)
		print(new_got)
	if __name__ == "__main__":
		main()

In the above example, I have used the definition of main(), which contains the program logic I want to run. I’ve also defined a function called ‘demo’, to include a piece of code, that can be reused as and when necessary. Furthermore, I have changed the conditional block, such that, it executes main().

In this way, I put the code I want to run within main(), the programming logic in a function called ‘demo’ and called main() within the conditional block. I have assimilated the output of the code and written it down below for your easy reference:

program3-Understanding main function in python 3-Edureka

Note: If you run this code as a script or if you import it, the output is going to be the same. You may look at the output below:

  • Call other functions from main().

When you write full-fledged Python programs, there could be numerous functions that could be called and used. More often than not, some functions should be called as soon as the execution of the program starts. Hence, it is always good to call other functions from the main() itself.

Let us look at below code fragment:

print("n Main Function Demo n")
	def demo(got):
		print("…Beginning Game Of Thrones Demo1…n")
		new_got = str.split(got)
		print("…Game of Thrones has finished…n")
		return new_got
	def getgot():
		print("…Getting GOT Data…n")
		got="Bran Stark wins the Iron Throne n"
		print("…GOT Data has been returned…n")
		return got
	def main():
		got= getgot()
		print(got)
		new_got = demo(got)
		print(new_got)
	if __name__ == "__main__":
		main()

In the above example, I have defined a function called “getgot()” to fetch the data. And this function is called from within the main() itself.

Hence, it is always good to call other functions from within the main() to compose your entire task from smaller sub-tasks, that can execute independently. I have also shared the output of the above code in the section below:

program5-Understanding main function in python 3-Edureka

I hope you were able to go through this article and get a fair understanding of what the main() function in Python is all about, and how it can be used. With the help of main() function in Python, we can execute a ton of functionalities as and when needed, and also control the flow of execution.

If you found this article on “Understanding Main Function in Python” relevant, check out the Edureka Python Certification Training, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. This training helps learners gain expertise in scripting in Python and prepare individuals to take up Python job opportunities.

Got a question for us? Please mention it in the comments section of “Main Function In Python” blog and we will get back to you at the earliest.

To get in-depth knowledge on Python Programming language along with its various applications, you can enrol here for live online training with 24/7 support and lifetime access.

Comments
0 Comments

Browse Categories

Subscribe to our Newsletter, and get personalized recommendations.