Python main() Function Purpose, Usage, and Examples

main() Function

Unlike many other programming languages, Python doesn't require a main function to start execution. That might sound liberating at first—but it also means structure is your responsibility.

This tutorial will help you understand how and why to use a main() function in Python. Whether you’re writing a script or building a module, learning to organize your code using main() and __name__ == "__main__" is a fundamental skill.

Why Use a main() Function in Python?

Python executes code from top to bottom. If you don’t take care, everything in your script might run immediately when imported elsewhere. To avoid this, we use a main guard pattern:

def main():
    print("Hello from main function!")

if __name__ == "__main__":
    main()

Understanding __name__ == "__main__"

Python assigns a special variable called __name__ to every module. When a script is run directly, __name__ is set to "__main__". But if the same script is imported, __name__ becomes the module's name.

Let's Break That Down:

# file: greet.py

print("This is always printed")

def hello():
    print("Hello!")

if __name__ == "__main__":
    print("This runs only when executed directly")

Now Run This:

import greet
This is always printed

Notice how "This runs only when executed directly" did NOT appear? That’s the power of __name__ == "__main__"—it guards what should only run in standalone mode.

Step-by-Step Guide to Using main()

Step 1: Define the Function

Create a main() function that wraps the core logic of your script.

def main():
    print("Starting the program")
    # Add your core logic here

Step 2: Add the Main Guard

Right at the bottom of your file, add the guard to control script behavior:

if __name__ == "__main__":
    main()

Step 3: Save and Run

Save your script as my_script.py and run it using:

python my_script.py
Starting the program

When to Use main()

  • Scripts: Whenever you’re writing a standalone script, wrap your logic inside main().
  • Modules: If your file might be imported later, using the guard prevents accidental execution.
  • Testing: It allows you to run quick tests when executing the file directly.

Common Mistakes to Avoid

  • Forgetting the Guard: If you don’t use __name__ == "__main__", your code may run unexpectedly during import.
  • Calling main() at the Top: Calling main() before defining it or outside the guard can lead to issues.
  • Naming Conflicts: Avoid naming variables or modules as main.

main() with Arguments

For more advanced Python scripts, especially command-line utilities, you can accept input parameters by using the sys.argv list from the sys module.

import sys

def main():
    print("Arguments passed:", sys.argv)

if __name__ == "__main__":
    main()

How It Works

  • sys.argv is a list that contains the command-line arguments passed to the script.
  • The first element, sys.argv[0], is always the name of the script.
  • Subsequent elements are the actual arguments provided by the user.

Example Usage:

If you run this script from the command line like this:

python my_script.py arg1 arg2

The output would be:

Arguments passed: ['my_script.py', 'arg1', 'arg2']

Why Use This?

This approach allows you to build flexible, CLI-based Python utilities that accept dynamic input from users, such as filenames, configuration flags, or processing options.

Conclusion

While Python doesn’t enforce a main() function like C or Java, learning to use it adds clarity, safety, and professionalism to your scripts. It’s one of those “small things” that sets experienced Python developers apart.

Always ask yourself: Could this code be imported in the future? If yes, then guard it well.

Mallikarjuna Mallisetty, author
About the author

Mallikarjuna Mallisetty

General programming

Mallikarjuna shares practical programming tutorials and foundational concepts designed to help developers learn by building and experimenting.

View LinkedIn profile ↗