EDUCBA

EDUCBA

MENUMENU
  • Blog
  • Free Courses
  • All Courses
  • All in One Bundle
  • Login
Home Software Development Software Development Tutorials File Handling Python Tutorial Python Main Method

Python Main Method

Priya Pedamkar
Article byPriya Pedamkar

Updated March 20, 2023

Python-Main-Method

Introduction to Python Main function

In general, all the programming languages have a main() function as a pre-defined function/ method to indicate to the compiler that it is the beginning of the execution flow. Python language is an exception to this, as its execution is in a serial manner, and the first line of the code will be the starting point by default. Despite the main() function not being a mandatory element, if the programmer wishes to have the main method to sort the other parts of the code, one can always create a user-defined method, which will operate similar to other methods python.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

How to declare the Python Main Function?

The main method is defined in a similar fashion to other functions defined in python.

1. Basic main function

print('Introduction to main() function')
def main():
    print("This is main function")
print('Outside main function')

Output: demo.py

>>>

=== RESTART: C:/Users/hp/AppData/Local/Programs/Python/Python37-32/demo.py ===

Introduction to main() function

2. Outside main function

>>>

Explanation: Python interpreter starts executing a python file from the top. First, it will print the first print statement, i.e. Introduction to main() function. It finds the main() method definition since it’s a mere definition and not a function call, so it bypasses this and executes the next print statement that follows this.

Note: In python, it doesn’t necessarily name the ‘main’ method as main(). It could be defined with any valid identifier name like main1(), main(), etc.

Execution of main() requires a brief understanding of the __name__ variable.

3. Brief about __name__ variable

__name__ variable is a special implicit variable containing a string, and the string’s value depends on how the code is being executed.

Basically, there are two ways in which python interpreters execute code and __name_ this populates_ value.

a. The most common way is to execute the file as a python script

In this case __name__ will contain the string “__main__”

b. By importing the necessary code from one python file to another file.

In this case __name__ will contain the imported module name

__name__ variable helps to check if the python file is being run directly or if it has been imported from some other file.

Examples of Python Main Method

Following are some examples of python main method:

1. Sum function: File is saved as sum_numbers.py

Python file: sum_numbers.py

def sum(a,b):
    return (a+b)
print(sum(3,6))
print("__name variable set to ",__name__)

The above program is the main program and is not imported from other python files, so the value of __name__ variable is set to __main__ as shown in the output below:

Output: sum_numbers.py

python main method output 1

2. When a python file is imported from another file

This file is saved as sum.py

Python file: sum.py

import sum_numbers
print(sum_numbers.sum(10.25,9.05))
print("value of __name__:",__name__)

Explanation:

  • Sum_numbers file is being imported in program file ‘sum.py’, so all the statements inside this are executed first.

i.e print(sum(3,6)) à  9

print(“__name variable set to “,__name__) à since this is being imported from sum_numbers so __name__ is set to sum_numbers

  • print(sum_numbers.sum(10.25,9.05)) à3

print(“value of __name__:”,__name__) à sum.py  is main file here so __name__  is set to __main__.

Output: sum.py

Sum.Py

To avoid the statements to get executed from the imported file ‘sum_numbers’ like in this case, we can use if conditional statements.

The below code example can illustrate this:

The above sum_numbers.py python file can be changed as below:

Python file: sum_numbers.py

def sum(a,b):
    return (a+b)
if __name__=='__main__':
    print(sum(3,6))
print("__name variable set to ",__name__)

Python file: sum.py

import sum_numbers
print(sum_numbers.sum(10.25,9.05))
print("value of __name__:",__name__)

In this case, output from imported file ‘sum_numbers.py’ is not printed when we execute sum.py because of this condition:

if __name__==’__main__’:

as this condition fails because sum_numbers is the imported module and not the main file.

Output: sum.py

python main method output 3

Key points to consider when main() is being used in the python program:

1. As python is an object-oriented programming language, we should incorporate its benefits into our program. This can be done by placing bulk logic codes in compact functions and/or classes for better code reusability, better debugging, a better understanding of the program and overall code optimization.

This approach will enable us to control our code’s execution rather than letting the python interpreter execute it.

This is best illustrated in the above code example, where we used if condition to prevent the output from the imported file.

2. Use __name__ variable to control the execution of code

If __name__=='__main__:
<logic of program>

3. Create main() function and put your logic inside this

Python file: demo.py

print("Main function illustration")
def sum(a,b):
    return (a+b)
def main():
    print("Inside main() function")
x=int(input("enter value x"))
y=int((input("enter value y")))
print("sum of values entered is",end=' ')
print(sum(x,y))
if __name__ == "__main__":
    main()
  • Here we have defined sum() and main().
  • Sum() will calculate the sum of two numbers,
  • Inside the main() method, we have prompted the user to enter values for x and y through the input() statement, which is then converted to integer values as input() returns string values.
  • Then sum(x,y) is called inside the main function, and control will transfer to the sum() method defined at the top, which will return the sum of the user’s numbers.
  • All the above functionalities are handled by the __name__ variable.
  • As demo.py is the main program file and is not being imported from any other python file, so __name__ is set to string __main__.
  • If there have been some import statements, then the below condition

If __name__ == “__main__”:

will fail as __name__ now will have the imported module name

In this way, I put the code which I wanted to run inside main(), programming logic in “SUM”, which is being called from main() and called the main() within the conditional statement.

Output: demo.py

Example 4 output

Conclusion – Python Main Method

Well, it’s not necessary to use the main() method in python, and it’s completely up to the programmer whether to have it in the code or not. However, it is good practice to use the main() method because with the help of the main() function; we can execute a ton of functionalities as and when needed and also control the flow of execution.

Recommended Article

This is a guide to Python Main Method. Here we discuss how to declare the Python Main Function along with the Examples and Outputs. You may also look at the following article to learn more –

  1. Python Built-in Functions
  2. Arrays in Python
  3. Sorting in Python
  4. Inheritance in Python
GOLANG Course Bundle - 6 Courses in 1
23+ Hours of HD Videos
6 Courses
Verifiable Certificate of Completion
Lifetime Access
4.5
iOS DEVELOPER Course Bundle - 61 Courses in 1
147+ Hours of HD Videos
61 Courses
Verifiable Certificate of Completion
Lifetime Access
4.5
JAVA SERVLET Course Bundle - 18 Courses in 1 | 6 Mock Tests
56+ Hours of HD Videos
18 Courses
6 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
RED HAT LINUX Course Bundle - 5 Courses in 1
28+ Hours of HD Videos
5 Courses
Verifiable Certificate of Completion
Lifetime Access
4.5
Primary Sidebar
Popular Course in this category
PYTHON Course Bundle - 81 Courses in 1 | 59 Mock Tests
 257+ Hours of HD Videos
81 Courses
59 Mock Tests & Quizzes
  Verifiable Certificate of Completion
  Lifetime Access
4.8
Price

View Course
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

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

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

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

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

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more