Yandex

Python main() Function
Purpose, Usage, and Examples



Introduction to Python's 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.

Advanced Tip: main() with Arguments

For more complex scripts, you might want to pass command-line arguments using sys.argv:

import sys

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

if __name__ == "__main__":
    main()
Arguments passed: ['my_script.py', 'arg1', 'arg2']

This gives you flexibility for CLI-based utilities.

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.

What’s Next?

Now that you’ve understood how main() works, try modifying a few of your older scripts. See the difference it makes in readability and modularity.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M