Python Introduction

Python Main Function

Knowing where the execution of a program starts helps us understand how a program works. Python offers us several conventions like the Python main function and the __name__ property to help us define the starting point of a program.

 

Python main

                                                                                                                                                            Source: cjsoftwarelogistics.com

What is the main() function in Python?

Most programming languages have a specific function known as main() that gets executed automatically when an operating system starts to run a program. The function marks the start of a program and usually has a specific return type and arguments based on the programming language standard. However, Python does not have any exclusive function that it automatically executes, and the interpreter executes scripts starting at the top of the file. 

We use the Python main function in the same format as any other declared function. 

                    

def main():
    print("Welcome, everyone!")
 
if __name__ == "__main__":
    main()

In the above example, the main() function prints the phrase “Welcome, everyone!” when the Python interpreter executes it. The conditional statement (if)checks the value of “__name__” and compares it to the string “__main__”. The interpreter executes the Python main when the if statement evaluates to True.

To help you understand how the above code exactly gets executed, you first need to understand how the Python interpreter sets __name__ based on the method of code execution. 

What is __name__ in Python?

__name__ is a unique Python variable that tells us the module name currently in use. We can check if the current script is running on its own or if it got imported from somewhere else. Python stores the __name__ variable in the global namespace with other attributes like __doc__, __package__, etc.

The __name__ variable gives us different values depending on where we execute or use the code. We use the command line to execute a Python file as a script. We can also import the program code from one Python file into another (or into the interactive interpreter).

So far, you have encountered words like file, script and module, but what is the difference between them? The three terms only have slight differences in their meaning. However, these differences stress the purpose of a piece of code.

Python main

  1. File: These are Python files that contain any piece of code and end with a .py extension. 
  2. Script: These are Python files that we execute from the command line to complete a task.
  3. Module: These are Python files that we import from another module, script, or from the interactive interpreter.

Now that we understand the difference between a file, script and module, let us see how a file is run as a script and a module.

Running Python File as a Script

                    

print("This file tests Python's execution methods.")
print("The variable __name__ tells us the context this file is running in.")
print("__name__ value is:", repr(__name__))

In the above example, we have defined three print commands. The first two are simple phrases, while the third one prints the representation of the __name__ variable using Python’s built-in repr().

repr() in Python gives us the printable representation of an object. We have used this function here to emphasize that the value of __name__ is a string.

We have defined the above three print statements in the execution_methods.py file and you can execute the script from the command line as shown below:

                    

$ python3 execution_methods.py
This file tests Python's execution methods.
The variable __name__ tells us the context this file is running in.
__name__ value is: '__main__'

Here, you may notice that the value of __name__ is ‘__main__’, where the quotes signify that the value is a string type.

Running Python File as a Module

When you are developing a module or a script, you may usually want to use the modules that someone else has already built. You can do this by using the import keyword, and that’s the second method the Python interpreter will execute your code. 

When we import a module, the Python interpreter executes statements that are defined in the specified module. However, it will do so only the first time you import the module and not every time. Let us import our execution_methods.py file in the Python interpreter.

                    

import execution_methods
This file tests Python's execution methods.
The variable __name__ tells us the context this file is running in.
__name__ value is: 'execution_methods'

In the above code, we get a different value for __name__(compared to what we got when we executed a file as a script). When the Python interpreter imports code, the value of __name__ is set as the name of the module that is being imported. Therefore, the value of __name__ is execution_methods which is the name of the .py file.

Using if conditional with __name__

Now that you have a grasp on how values are assigned to the __name__ variable, you can start using conditional statements like if statements to run codes in a different context. 

Let us take an example where we change the content of the welcome.py file to the following:

                    

def main():
    print("Welcome, everyone!")
 
if __name__ == "__main__":
    main()

If we run this file as a script through the command line, we get the following output:

However, if we import the file as a module, we will not get any output since we did not call the main() function. As we have created a custom main() function in the welcome.py, it will only execute when the program is run as a stand-alone script and not as an imported module.

Questions and Answers

Q1. What is Python __ main __?

A Python interpreter can run code in two ways: as a script or as a module. When the interpreter runs a file as a script in the command line, the value of __name__ variable is set to __main__.

Q2. Where is the main function in Python?

The Python main function is actually like the entry point of a program. However, in Python, the interpreter executes a script starting at the top of the file in a sequence. Although we can define a custom main function in a file, it is not required.

Q3. Is there a main in Python?

Most programming languages have a specific function called main() that gets executed automatically when a program starts. However, Python does not have any exclusive function that it automatically executes. The interpreter starts executing code that is at level 0 indentation.

Q4. How do you write main in Python?

We write the main function like any other function in Python. 

                    

def main():
    print("Howdy, everyone!")
 
if __name__ == '__main__':
    main()

You can use the following steps to make sure your code can serve a dual purpose:

  1. Define most of the code in a function or class.
  2. Control the execution of your code via __name__ variable.
  3. Create a main() function to contain your code.
  4. Use main() to call other functions.
Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

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

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.