MyInternships.in

Python Modules & Packages

Python main Function

The line if __name__ == "__main__": lets a Python file behave differently depending on whether it is run directly or imported by another file.


The Hidden __name__ Variable

Every Python file automatically gets a built-in variable called __name__. When you run a file directly, Python sets __name__ to the string "__main__". When that same file is imported as a module into another file, __name__ is set to the module's filename instead.

Checking __name__
Python
print(__name__)

Why This Check Exists

Suppose you write a module full of useful functions, and also add some test code at the bottom to try them out. Without a guard, that test code runs every single time someone else imports your module — which is rarely what you want. Wrapping it in if __name__ == "__main__": ensures it only runs when the file is executed directly.

A Practical Example

calculator.py
Python
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

if __name__ == "__main__":
    print(add(4, 5))
    print(subtract(10, 3))

Run this file directly and you see the print output. But if another file does import calculator, only the functions become available — the test prints do not run.

other_file.py
Python
import calculator

result = calculator.add(2, 2)
print(result)

Script vs Module Behaviour

This single check is what allows one Python file to work both as a standalone script and as a reusable module elsewhere — a pattern you will see in almost every serious Python project, including packages and command-line tools.

💡

Put your "entry point" logic, like calling a main() function, inside the __name__ == "__main__" block so it stays clean and testable.

A common pattern
Python
def main():
    print("Program started")

if __name__ == "__main__":
    main()

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships