LearnPython.com
  • Courses
  • Articles
  • Log in
  • Create free account
  • fullName

    User profile menu open Open user profile menu avatar
    avatar
    fullName
    Dashboard
    My Profile
    Payment & Billing
    Log out
MENU CLOSE
  • Courses
  • Articles
  • Dashboard
  • My Profile
  • Payment & Billing
  • Log in
  • Create free account
  • Log out 
Back to articles list Articles
25th May 2022 6 minutes read

How Do You Write a Main Function in Python?

Author's photo
Kateryna Koidan
  • python
  • main function
See More

If you are just starting with Python, you might not be aware yet of the best practice of defining functions. In this guide, I’ll explain how including a main() function, though not required in Python, can structure your programs in a logical way and ensure that your functions are executed only when expected.

The Python ecosystem is very rich in modules, packages, libraries, and frameworks. It is sometimes challenging for beginners to understand the difference between these concepts, but basically they’re all forms of organizing Python code.

For example, a module is a bunch of related code saved in a file with the extension .py. With a custom module in Python, you can define variables, functions, or even create your own classes. You can include runnable code in modules. However, if a module with runnable code is imported from a different module, this code would execute itself when it is imported.

In this article, I’ll discuss how to avoid this situation by adhering to the Python  best practice of separating code that should be executed only when it is run as a script (but not when it’s imported).

After you read this guide, I encourage you to start practicing right away with the interactive learning track Learn Programming with Python. It includes hundreds of coding challenges covering this language’s basics as well as more advanced concepts for writing optimized Python applications.

Python Top-level Code Environment

Module objects in Python are characterized by various attributes that are prefixed and postfixed by a double underscore ('__'). The key attribute of each module is its name – or more precisely, __name__.

In any module you import, its name will be set to the name of the file. For example, if you import the NumPy module, you’ll see that its attribute __name__ will be equal to numpy:

>>> import numpy
>>> print(numpy.__name__)

Output:

numpy

The important thing to remember is that when Python is running as a top-level executable code (i.e. when read from standard input, a script, or an interactive prompt), the __name__ attribute is set to '__main__'. So, we can literally say that, in the top-level script environment, __name__ = '__main__'.

Why not use this knowledge to separate the code in your module that is intended for script use only? Good coding practices suggest using the following if code block …

if __name__ == '__main__' 

.. and including there the code that we only want to run when the module is executed in the top-level environment.

Let’s see how this works with a few examples.

Good Practices of Organizing Code When Defining a Function

We’ll start with a basic example to demonstrate how you can separate executable code in your module. Then, we’ll move to a more complex example, where we’ll define a main() function.

Example 1. Separating executable code

Let’s say we are developing a game that only people aged 18+ are allowed to play. The age variable is declared in the top-level environment by getting input from the user:

# Declare global variable age
age = int(input('Please enter your age in years: '))

Then, we have a called module age_check.py that has the following code:

# Define a function to check that age is 18+
def age_check(age):
    if age >= 18:
        print('You are allowed to enter the game.')
    else:
        print('You are not allowed to enter the game.')
        
# Execute age_check() function
age_check(age)

As you see, this module has an executable piece of code after the age_check() function is defined. Hence if we import age_check.py, its code will be run automatically. To avoid this, you can put the executable code separately in the if __name__ == '__main__' code block:

# Define a function to check that age is 18+
def age_check(age):
    if age >= 18:
        print('You are allowed to enter the game.')
    else:
        print('Unfortunately, you are not allowed to enter the game because of the age restriction.')
        
#Execute age_check() function
if __name__ == '__main__':
    age_check(age)

In such a case, you can import the age_check() module without the runnable code being executed. Everything within the if __name__ == '__main__' block won’t run unless the module is executed in the top-level environment.

Example 2. Defining the main function in Python

In our first example, I’ve demonstrated the key principle of how we can separate executable code so that it runs only when executed in the top-level environment. However, in practice, modules often define many different variables, functions, and classes. You may also have several unrelated pieces of runnable code within one module. So, to improve code clarity and correctness, it’s a best practice to put as few statements as possible in the block below if __name___ == '__main__'. Most often, a function named main() encapsulates the program’s primary behavior.

For example, let’s say we want to write a Python module that greets new members and checks their age. First, we have the name and age variables declared in the top-level code environment:

name = str(input('Please enter your name: '))
age = int(input('Please enter your age in years: '))

Then, we can have the following welcome.py module imported:

# Define a function to greet new players
def greeting(name):
    print ("Hi {}. Glad to see you here.".format(name))

# Define a function to check that age is 18+
def age_check(age):
    if age >= 18:
        print('You are allowed to enter the game.')
    else:
        print('Unfortunately, you are not allowed to enter the game because of the age restrictions.')

# Define main function
def main():
    greeting(name)
    age_check(age)

# Execute main() function
if __name__ == '__main__':
    main()

As you see, we first define two separate functions to greet new players and to check their age. Next, we define the main() function, which contains a call to the greeting() and age_check() functions. Finally, we add the if __name__ == '__main__': code block at the end of the file.

Since we have all the functions we would like to run in the main() function, we only call the main() function following this if statement. Since all the runnable code is placed under the if statement, it will not be executed during the module import.

Of course, you can always choose NOT to declare a main() function and have the following code block instead:

if __name__ == '__main__':
    greeting(name)
    age_check(age)

However, best practices suggest using the main() function. Defining the main function in Python and then using it in the if __name__ == '__main__': statement allows you to organize your code logically and make it more readable and easier to follow. This would be particularly obvious with complex modules that define several functions and/or classes.

You might be also interested in making your code more professional and cleaner-looking with our guide to the argparse module.

Time to Practice Main Functions in Python!

To master any new skill, you need lots of practice. When it comes to practicing Python, I think interactive online courses are the best option for beginners. With a good course, you have all the coding examples prepared for you. Hence, you can focus on the new concepts you’re learning, without the need to set up a Python coding environment and search for projects to practice.

For aspiring Python programmers, I recommend our interactive learning track  Learn Programming with Python. It includes five courses covering the very basics (defining variables, writing conditional statements and loops, etc.), more advanced concepts, and advice on best coding practices.

Thanks for reading, and happy learning!

Bonus. Here’s the list of the most popular Python packages.

Tags:

  • python
  • main function

You may also like

Python Modules, Packages, Libraries, and Frameworks
Let’s discuss the difference between Python modules, packages, libraries, and frameworks – in simple terms and with multiple examples.
Read more
How to Write a Custom Module in Python
Learn what a custom module is in Python, why you would want to write one, and how to write one.
Read more
Simple Steps for Creating Your Own Class in Python
Learn what a custom class is in Python and discover how to create classes and custom objects in Python.
Read more
A Guide to the Python argparse Module
Discover how to build a command-line interface with the Python argparse module.
Read more
Most Popular Python Packages in 2021
Python packages help data analysts and developers efficiently complete complex tasks. Here’re the packages you should know about in 2021.
Read more
Python vs. Java: Which Should You Learn as a Beginner?
Python vs. Java? Explore key application areas, syntax differences, and expected salary levels to help you pick your first programming language.
Read more
Top 5 Python Learning Platforms for Beginners
If you want to be a programmer, start with Python! See which e-learning Python platform is the best for you.
Read more
Subscribe to our newsletter Join our monthly newsletter to be notified about the latest posts.

How Do You Write a SELECT Statement in SQL?

What Is a Foreign Key in SQL?

Enumerate and Explain All the Basic Elements of an SQL Query

Quick links

  • Pricing
  • Blog
  • Vertabelo.com

Assistance

Need assistance? Drop us a line at [email protected]

Write to us

Follow us

LearnSQL Facebook We Learn SQL Facebook Linkedin LearnPython.com We Learn SQL Youtube
go to top
Copyright ©2016-2018 Vertabelo SA All rights reserved
Vertabelo
  • Terms of service
  • Privacy policy
  • Imprint