- How Do You Write a Main Function in Python?
- Python Top-level Code Environment
- Good Practices of Organizing Code When Defining a Function
- Example 1. Separating executable code
- Example 2. Defining the main function in Python
- Time to Practice Main Functions in Python!
- Python Main Function & Method Example: Understand def Main()
- def main() Example 1
- def main() Example 2
- The __name__ variable and Python Module
How Do You Write a Main Function in Python?
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__)
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 …
.. 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.
Python Main Function & Method Example: Understand def Main()
Python main function is a starting point of any program. When the program is run, the python interpreter runs the code sequentially. Main function is executed only when it is run as a Python program. It will not run the main function if it imported as a module.
What is the def main() function in Python? To understand this, consider the following example code
def main() Example 1
def main(): print ("Hello World!") print ("Guru99")
Here, we got two pieces of print- one is defined within the main function that is “Hello World!” and the other is independent, which is “Guru99”. When you run the function def main ():
It is because we did not declare the call function “if__name__== “__main__”.
It is important that after defining the main function, you call the code by if__name__== “__main__” and then run the code, only then you will get the output “hello world!” in the programming console. Consider the following code
def main() Example 2
def main(): print("Hello World!") if __name__ == "__main__": main() print("Guru99")
- When Python interpreter reads a source file, it will execute all the code found in it.
- When Python runs the “source file” as the main program, it sets the special variable (__name__) to have a value (“__main__”).
- When you execute the main function in python, it will then read the “if” statement and checks whether __name__ does equal to __main__.
- In Python “if__name__== “__main__” allows you to run the Python files either as reusable modules or standalone programs.
The __name__ variable and Python Module
To understand the importance of __name__ variable in Python main function method, consider the following code:
def main(): print("hello world!") if __name__ == "__main__": main() print("Guru99") print("Value in built variable name is: ",__name__)
Now consider, code is imported as a module
import MainFunction print("done")
Here, is the code explanation:
Like C, Python uses == for comparison while = for assignment. Python interpreter uses the main function in two ways
import as a module
- __name__= module’s filename
- if statement == false, and the script in __main__ will not be executed
When the code is executed, it will check for the module name with “if.” This mechanism ensures, the main function is executed only as direct run not when imported as a module.
Above examples are Python 3 codes, if you want to use Python 2, please consider following code
def main(): print "Hello World!" if __name__== "__main__": main() print "Guru99"
In Python 3, you do not need to use if__name. Following code also works
def main(): print("Hello World!") main() print("Guru99")
Note: Make sure that after defining the main function, you leave some indent and not declare the code right below the def main(): function otherwise, it will give indent error.