Concept of __main__

Every Python file has a built-in variable called __name__. Its value changes depending on how the file is being used, and checking it lets you control exactly what code should run.

How __name__ Works

When a file is run directly, Python sets __name__ to "__main__". When the same file is imported into another script instead, __name__ is set to the module's name.

print("This file's name is:", __name__)

The if __name__ == "__main__" Pattern

def main():
    print("Running the main program")

if __name__ == "__main__":
    main()

Why This Matters

  • Lets a file be reused as an importable module without automatically running its script logic
  • Keeps test or demo code separate from reusable functions
  • Widely used as standard practice in real Python projects and packages
You'll see the if __name__ == "__main__": pattern in almost every serious Python project, since it clearly separates code meant to run directly from code meant to be imported.

You've Completed This Section

You now have a solid grip on Python fundamentals, from why programming matters to working with data structures, functions, and how Python scripts are executed. This foundation prepares you for the deeper data science concepts covered next in the full course.

Ready to Master Data Science?

Join Uncodemy's Data Science Course and build real, job-ready skills with expert mentors.

Explore Course