Understanding Python's Main Function: A Practical Guide to def main()
What is the Python Main Function?
The main function in Python marks the entry point of a program. When a script is executed directly, the interpreter runs code sequentially. Code inside def main() runs only if the script is the primary module, not when imported elsewhere.
Let’s walk through a clear example.
Example 1: Defining main()
def main():
print("Hello World!")
print("Guru99")
Running this file prints only Guru99. The Hello World! line remains inside main() and is never called.
To execute main() when the script runs as the main program, you must guard it with:
if __name__ == "__main__":
main()
Now the script behaves as expected.
Example 2: Proper Guarding
def main():
print("Hello World!")
if __name__ == "__main__":
main()
print("Guru99")
When you run this file, the console displays:
Hello World!
Guru99
Why does this work? The interpreter sets the special variable __name__ to "__main__" when a file is executed directly. The guard checks that condition before calling main().
The Role of __name__ and Modules
Understanding __name__ is essential for writing reusable code.
def main():
print("hello world!")
if __name__ == "__main__":
main()
print("Guru99")
print("Value in built variable name is: ", __name__)
Running the file directly prints the two messages and __name__ as "__main__". If you import this script as a module:
import mainfunction
print("done")
you’ll see only done and __name__ will reflect the module name, so main() does not execute automatically.
In short:
- Direct run:
__name__ == "__main__"→main()runs. - Import as module:
__name__ != "__main__"→main()is skipped.
Python 3 doesn’t require if __name__ == "__main__": for simple scripts, but using the guard is a best practice, especially when the file may be reused. In Python 2, the syntax remains the same, but print statements differ:
def main():
print "Hello World!"
if __name__ == "__main__":
main()
print "Guru99"
In Python 3, you can also write:
def main():
print("Hello World!")
main()
print("Guru99")
Remember: always maintain proper indentation after the def main(): line to avoid errors.
Python
- Master Python Functions: Syntax, Types, and Practical Examples
- Mastering Python Function Arguments: Positional, Keyword, and Default Parameters
- Mastering Python Recursion: How Functions Call Themselves
- Python Lambda Functions: A Practical Guide to Anonymous Functions
- Python Closures Explained: How Nested Functions Capture Variables
- Mastering Python’s strip() Method: Comprehensive Guide & Practical Examples
- Python len(): A Practical Guide to Measuring Object Lengths
- Mastering Python’s Yield: Generator vs Return – A Practical Guide
- Mastering Python’s enumerate(): Loop with Indices for Lists, Tuples, Strings, and Dictionaries
- Python time.sleep(): How to Add Delays in Your Code (Example)