- Python Main Functions: A How-To Guide
- How to Use Python Main Functions
- What is the Python main() Function?
- Main Function Python: Walkthrough
- What is Python __name__?
- What is if __name__ == __main__?
- Python if __name__ == __main__ Example
- Conclusion
- What’s Next?
- Get matched with top bootcamps
- Ask a question to our community
- Take our careers quiz
- Leave a Reply Cancel reply
- Related Articles
- Python Main Function & Method Example: Understand def Main()
- def main() Example 1
- def main() Example 2
- The __name__ variable and Python Module
Python Main Functions: A How-To Guide
The Python main() method contains the methods and code you want to execute in a main program. It is not necessary because Python runs code line-by-line but the main() method helps make code more readable.
How to Use Python Main Functions
“I’ve seen a few tutorials that use main() in Python. What does it mean?” That’s a great question. The main() function may seem trivial when it’s not actually necessary.
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
Coding is all about being concise; you’re probably curious why developers want to add in more lines of code into a program. The main() function may add an extra few lines of code into your Python program, but it does serve an important purpose.
In this guide, we’re going to talk about what the main() function is and why it is useful.
What is the Python main() Function?
The Python main() function lets you introduce logic into your Python programs. A main() function is executed as soon as a program is run. It defines the order in which particular functions should be executed.
The syntax for the main() function is:
The main() function appears at the bottom of a program, after all modules have been imported and functions have been declared.You can call a Python function at the bottom of your program and it will run. But, it can be quite confusing that the code at the bottom of a program is the main program. In other programming languages like C++ and Java, all the main code for a program is contained within a main function.
A main() function a good way of breaking down all the code in your programs. People who are new to Python but who know other programming languages like C++ will thank you for adding in a main() function.
Main Function Python: Walkthrough
There are two parts of a Python main function. The first part is the actual main() function which stores the code for our main program. Let’s call our cookies() function and print out the statement: “I like cookies.” from within a main() function:
def cookies(): print("Cookies are delicious!") def main(): print("I like cookies.") cookies()
Finally, let’s call our function at the bottom of our program:
Cookies are delicious! I like cookies!
It is clear exactly what is happening in our program:
- Cookies() is a function that prints “Cookies are delicious.”
- When our program is run, our two functions, cookies() and main(), are defined.
- Then we call the main() function.
- “I like cookies.” is printed to the console.
- The cookies() function is then called, printing “Cookies are delicious!” to the console.
Our code is not only cleaner, but it’s also more logical. If you come from another language like Java, you’ll know how useful this is.
What is Python __name__?
The Python __name__ statement refers to the name of a script. If you run a program as a module, it will take on the name of the module. Otherwise, __name__ will have the value __main__, which refers to the program you are running.
Before we talk about the __name__ and __main__ statements that are often used together with a main function, we’ve got to talk about __name__. __name__ stores the name of a program.
When you run a file directly, __name__ is equal to __main__. Consider this file called print_name.py:
We can run our code like this:
Our code returns: __main__.
Suppose we were to import this as a module into a file called main.py. Let’s create a file called main.py and import the print_name module:
The code within our print_name.py file is executed because we imported it as a module in our main program. The print_name.py file prints __name__ to the console. Because we imported print_name as a module, the value of __name__ is print_name.
What is if __name__ == __main__?
The Python if __name__ == __main__ statements execute the code they contain if you run a file directly. This statement prevents some code from executing if a program is called as a module.
You’ve probably seen something like this in a Python program with a main function:
What does this mean? That’s another good question. In Python, any variable that starts and ends with __ is a special variable. These are reserved values that have specific purposes in a Python program.
__main__ refers to the scope where your code will execute. When you run a Python file directly, the value of “__name__” is set to “__main__”. However, when you run a file as a module, the value of “__name__” is not “__main__”; it is set to the name of the module.
This means that the line of code above will evaluate to True when our program is run. But, this line will only evaluate to True if we run our program directly from the command line instead of from a Python module.
«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»
Venus, Software Engineer at Rockbot
If we reference our file as a module, the contents of the Python “if” conditional statement will not be executed. Let’s demonstrate how this works with an example.
Python if __name__ == __main__ Example
Let’s create a new Python script called username.py. In this file, we’re going to ask a user to select a username and check if it is more than five characters long. If the username is not longer than five characters, the user will be asked to choose a new username.
We’ll start by defining a global variable to store our user’s username:
We’re going to define two functions. The first function will ask a user to select a username and check if it is more than five characters long. The second function will print out that username to the Python shell:
def choose_username(): global username username = input("Choose a username: ") if len(username) > 5: print("Your username has been selected.") else: print("Please choose a username greater than five characters long.") choose_username() def print_username(): print(username)
We’ve used the Python “global” keyword so that the contents assigned to the “username” variable inside the choose_username() method will be accessible globally. Now that we’ve defined our functions, we’re going to create a main function which calls these functions:
def main(): choose_username() print_username()
We’re then going to add in the if __name__ = ‘__main__’ statement. This means that if we run our source file directly, the Python interpreter executes our two functions. If we run it as a module, the contents of our main() method will not execute.
if __name__ == "__main__": main()
Choose a username: CareerKarma Your username has been selected. Career Karma
Our code runs the choose_username() function, and then executes the print_username() function. If we select a username that is fewer than four characters, we’ll see a response like this:
Choose a username: CK Please choose a username greater than five characters long. Choose a username:
We’re prompted to choose another username.
If we were to import this code as a module, our main() function would not run.
Conclusion
The main() function is used to separate blocks of code within a Python program. While it’s not necessary to write a main() function in Python, writing one is a good way to improve the readability of your code.
Writing a main() function is mandatory in languages like Java, on the other hand. A main() function it makes it clear in what order lines of code run within a program. Including a main() function in your program is a good practice for all programmers for this reason.
Now you’re ready to start writing and working with main methods in Python like a professional! For more Python learning resources, check out our How to Learn Python guide.
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.
What’s Next?
Get matched with top bootcamps
Ask a question to our community
Take our careers quiz
James Gallagher is a self-taught programmer and the technical content manager at Career Karma. He has experience in range of programming languages and extensive expertise in Python, HTML, CSS, and JavaScript. James has written hundreds of programming tuto. read more
Leave a Reply Cancel reply
Related Articles
At Career Karma, our mission is to empower users to make confident decisions by providing a trustworthy and free directory of bootcamps and career resources. We believe in transparency and want to ensure that our users are aware of how we generate revenue to support our platform.
Career Karma recieves compensation from our bootcamp partners who are thoroughly vetted before being featured on our website. This commission is reinvested into growing the community to provide coaching at zero cost to their members.
It is important to note that our partnership agreements have no influence on our reviews, recommendations, or the rankings of the programs and services we feature. We remain committed to delivering objective and unbiased information to our users.
In our bootcamp directory, reviews are purely user-generated, based on the experiences and feedback shared by individuals who have attended the bootcamps. We believe that user-generated reviews offer valuable insights and diverse perspectives, helping our users make informed decisions about their educational and career journeys.
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
Find a top-rated training program
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.