EDUCBA Logo

EDUCBA

MENUMENU
  • Explore
    • EDUCBA Pro
    • PRO Bundles
    • Featured Skills
    • New & Trending
    • Fresh Entries
    • Finance
    • Data Science
    • Programming and Dev
    • Excel
    • Marketing
    • HR
    • PDP
    • VFX and Design
    • Project Management
    • Exam Prep
    • All Courses
  • Blog
  • Enterprise
  • Free Courses
  • Log in
  • Sign Up
Home Software Development Software Development Tutorials File Handling Python Tutorial Python if main
 

Python if main

Priya Pedamkar
Article byPriya Pedamkar

Updated March 27, 2023

Python if main

 

 

Introduction to Python If Main

The sole purpose of any program which we write is to have hassle-free execution of the same. The main function in Python acts as a point of execution for any program. A program gets executed only when it is executed from the main function, and it does not get executed when it is imported as a module. Defining Python’s main function is not mandatory, but it is a good practice to do so for better readability of your program. The main function is denoted by the following keyword main(). Let us have a look at the syntax and a basic example of Python main function.

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

Python Execution Modes

There are mainly two ways by which we tell the Python interpreter to execute the program:

  1. Directly executing the Python file.
  2. Importing an external Python file as a package and then using the function from that file.

When we want to execute the Python script directly, then Python will assign “__main__” to __name__ as we will see in the below example.

The conditional if statement, when evaluated to True, means that the Python script will execute directly. Thus, the conditional if the statement is written at the end after all other functions and classes have been defined. The function of the __name__ variable is to check whether the file is being run directly or it is being imported.

Executing by Importing the necessary code from one Python file to another

Syntax:

module1.py
def function1():
  // function1 definition
if __name__ == "__main__":
  function1()
import module1
module1.function1()

Example Code:

# module1.py
import numpy as np
def get_square(number):
  square = np.square(number)
  return square
if __name__ == "__main__":
  get_square(5)
import module1
module1.get_square(5)

In the above example, we have defined a function get_square that accepts a number as an argument and returns that number’s square. We have saved that file as module1.py.

We are using the get_square function in the main function by importing the module1 script as a module.

Best Practices for Writing Main functions

The following are the best practices that are to be considered while writing the main function in Python: –

1. We must use functions and classes wherever we feel necessary

Since Python is an Object-Oriented programming language, we must take full advantage of it and different functionalities under different classes and functions. This helps in better reusability and readability of the code. In this way, the execution of the code is also controlled.

Code:

import numpy as np
def get_square(number):
    print("The square of {} is :".format(number))
    square = np.square(number)
    return square
print("Using function :")
square=get_square(5)
print(square)

Output:

Python if main output 1

2. We must use the variable “__name__” to control the execution of our code

The variable __name__, when used with a conditional if statement when, evaluates to True, then only the next statements get executed. This way, the flow of execution of the code is better handled.

Code:

def main():
    print("Programming in Python is fun!!!")
    if __name__== "__main__" :
main()

Output:

Python if main output 2

In the above example, there is a function called main(). Inside the main function, we have a print function. After that, we have a conditional if statement which checks whether the value of __name__ is equal to the string “__main__”. Once the condition is evaluated to True, it executes the main() function, and thus the print statement “Programming in Python is fun!!!” gets executed.

3. We must use the main function

A code written inside the main function gets executed even if it has not been called explicitly. It is the starting point of every execution process. The common piece of code which is always supposed to be executed must be placed inside the main function. In this way, the main function statements get executed first and then the rest statements are executed.

Code:

import numpy as np
def get_square(number):
    print("Inside the first function")
    print("The square of {} is :".format(number))
    square = np.square(number)
    return square
def main(number):
  print("Inside the main function")
  square_root = np.sqrt(number)
  print("The square root of {} is {}".format(number,square_root))
  square = get_square(number)
  print(square)
if __name__ == "__main__":
    main(5)

Output:

Square Root Function

4. We must call other functions from the main function

For large chunks of code to be executed in the main function, it is good to place them in separate functions and call them explicitly from the main function. It increases the robustness and readability of your program.

Code:

import numpy as np
def get_square(number):
  print("Inside the square function")
  print("The square of {} is :".format(number))
  square = np.square(number)
  return square
def get_square_root(number):
  print("Inside the square root function")
  print("The square root of {} is :".format(number))
  square_root = np.sqrt(number)
  return square_root
def main(number):
  print("Inside the main function")
  square_root = get_square_root(number)
  print(square_root)
  square = get_square(number)
  print(square)
if __name__ == "__main__":
  main(5)  

Output:

Square Function

Conclusion

It is time to draw closure to this article. In this article, we have seen the basic concepts of if the main function in Python. We have looked at the Syntax and discussed the different examples related to it. Next time you write a code in Python, do remember to keep these concepts in mind.

Recommended Articles

This is a guide to Python if main. Here we discuss the two ways of Python interpreter to execute the program along with the respective examples. You may also have a look at the following articles to learn more –

  1. Python Subprocess
  2. Python Set Function
  3. Python List Functions
  4. Python Countdown Timer

Primary Sidebar

Footer

Follow us!
  • EDUCBA FacebookEDUCBA TwitterEDUCBA LinkedINEDUCBA Instagram
  • EDUCBA YoutubeEDUCBA CourseraEDUCBA Udemy
APPS
EDUCBA Android AppEDUCBA iOS App
Blog
  • Blog
  • Free Tutorials
  • About us
  • Contact us
  • Log in
Courses
  • Enterprise Solutions
  • Free Courses
  • Explore Programs
  • All Courses
  • All in One Bundles
  • Sign up
Email
  • [email protected]

ISO 10004:2018 & ISO 9001:2015 Certified

© 2025 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA Login

Forgot Password?

🚀 Limited Time Offer! - 🎁 ENROLL NOW