Python

Use of the ‘if __name__ == __main__’ Statement in Python

Some special variables are set when any Python script executes. The __name__ variable is one of them. The Python file is saved with the ‘.py’ extension and each Python file is called a module. The classes, functions, and variables are defined by the module. The __name__ variable is set to __main__ if the Python interpreter runs a module in the main program. The __name__ variable is set to the module’s name if the Python file is importing the module from another module. The ‘if __name__ == __main__’ statement is used to check if the module is imported or not. Different uses of this statement have been shown in this tutorial.

Example-1: Simple Use of the __name__ Variable

Create a Python file with the following script that calls the main() function if the value of the __name__ variable is __main__. The main() function has been declared in the script to define the statements. A string value and a number value will be printed after calling the main() function. No module has been imported into the script. So, the ‘if’ statement will be returned True and the main() function will be called.

#Define the main function

def main():

#Print a simple message

print("Testing the use of __name__ variable.")

#Initialize the variable with the number

n = 15

#Print the value of the variable

print("The value of n is ", n)

#Check the value of __name__

if __name__ == "__main__" :

#Call the main() function

main()

Output:

The following output will appear after executing the above script. The output shows that the ‘if’ condition has returned True and the main() function has been called.

Example-2: Print the Value of the __name__ Variable

Create a Python file with the following script that calls the main() function if the value of the __name__ variable is __main__, like the previous example. Two number values will be taken from the user and print the sum of the numbers after calling the main() function. The ‘if’ condition will check the value of the __name__ variable. If the condition returns True, then a message will be printed, the value of the __name__ variable will be printed, and the main function will be called. If the condition returns False, then a message will be printed and the value of the __name__ variable will be printed.

#Define the main function

def main():

#Print a simple message

num1 = int(input("Enter the first number: "))

num2 = int(input("Enter the second number: "))

sum = num1 +num2

#Print the value of sum

print("The sum of %d and %d is %d" %(num1, num2, sum))

#Check the value of __name__ variable

if __name__ == "__main__":

print("Python interpreter has called directly.")

print("The value of __name__ variable is "+__name__)

main()

else:

print("Python interpreter has not called directly.")

print("Value of __name__ attribute is "+__name__)

Output:

The following output will appear after executing the above script. The output shows that the main() function has been called because the value of the __name__ variable is __main__. 7 and 9 have been taken as input from the user and the sum of 7 and 9 which is 16, has been printed in the output.

Example-3: Use of the __name__ Variable with Class

Create a Python file with the following script that defines a class to calculate the area of the circle and the rectangle. If the value of the __name__ variable is __main__, then the input will be taken from the user. Next, the object of the class will be created. The circle_area() method will be called if the input value is ‘circle’. The rectangle_area() method will be called if the input value is ‘rectangle’. A message will be printed if the input value does not match with the ‘circle’ or ‘rectangle’.

#Declare the class

class CalculateArea:

#Declare constructor

def __init__(self, type):

self.type = type

#Declare method for calculating circle area

def circle_area(self, radius):

self.radius = radius

area = 3.14 * self.radius * self.radius

print("The area of the circle is ", area)

#Declare method for calculating rectangle area

def rectangle_area(self, h, w):

self.height = h

self.width = w

area = self.height * self.width

print("The area of the rectangle is ", area)

#Check the __name__ variable

if __name__ == '__main__':

areaType = input("Circle or Rectangle?\n")

object = CalculateArea(areaType.lower())

if object.type == 'circle':

object.circle_area(4)

elif object.type == 'rectangle':

object.rectangle_area(10, 20)

else:

print("No matching type found.")

Output:


The following output will appear after executing the above script. In the following output, the ‘circle’ has been taken as the input value and the area of the circle of radius 4 has been printed in the output.

In the following output, the ‘rectangle’ has been taken as the input value and the area of the rectangle (the height value, 10 and the width value, 20) has been printed in the output.

In the following output, the ‘square’ has been taken as an input value that does not match with ‘circle’ or ‘rectangle’.

Example-4: Use of the __name__ Variable After Importing a Module

Create a Python file named file1.py with the following script that will be imported into another Python file. This script will print a simple message, and a message based on the __name__ variable.

file1.py

# Python file one module

#Print a simple message

print("Message from file1.py")

#Print the value of __name__ variable

print("The value of __name__ is ", __name__)

if __name__ == "__main__":

print("Python interpreter has called directly.")

else:

print("Python interpreter has not called directly.")

Create another Python file with the following script that will import the file1.py as a module in the script. This script will print a simple message, and a message based on the __name__ variable after importing the file1 module.

#Import file1.py

import file1

#Print a simple message

print("Welcome to LinuxHint")

#Print the value of __name__ variable

print("The value of __name__ is ", __name__)

if __name__ == "__main__":

print("Python interpreter has called directly.")

else:

print("Python interpreter has not called directly.")

Output:


The following output will appear after executing the above script. The output shows that the value of the __name__ variable is changed to the module name after importing another module in the script.

Conclusion

The purpose of using the __name__ variable has been explained in this tutorial by using different types of examples to help the users to use it in their script properly.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.