codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🐍

Python Programming

41 / 68 topics
36List Comprehensions37Python Iterators38Python Generators39Python Decorators40Python Modules, Packages & PIP41Python Main Function (__name__ == '__main__')42Python Dates and Time43Python Regular Expressions44Python JSON
Tutorials/Python Programming/Python Main Function (__name__ == '__main__')
🐍Python Programming

Python Main Function (__name__ == '__main__')

Updated 2026-05-15
30 min read

Python Main Function (name == 'main')

In this tutorial, we will explore the __name__ variable in Python and how it is used with the if __name__ == "__main__" idiom. Understanding these concepts is crucial for structuring your Python scripts effectively, distinguishing between scripts and modules, and implementing the main() function pattern.

Introduction

When you run a Python script, Python assigns special names to certain variables. One of these is __name__. The value of __name__ depends on how the file is being used:

  • If the file is executed as a standalone program (i.e., not imported), __name__ is set to '__main__'.
  • If the file is imported as a module in another script, __name__ is set to the name of the module.

This distinction allows you to write code that behaves differently depending on whether it's being run directly or imported. The if __name__ == "__main__" idiom is a common pattern used to separate executable code from reusable code, making your scripts more modular and maintainable.

Core Content

Understanding the name Variable

The __name__ variable is a built-in variable in Python that holds the name of the current module. When you run a Python file directly, it is considered the main program, and __name__ is set to '__main__'. If the same file is imported as a module in another script, __name__ will be set to the module's name.

Example 1: Basic Usage of name

Let's create a simple Python script named greeting.py.

greeting.py
1def greet():
2 print("Hello!")
3
4if __name__ == "__main__":
5 greet()

When you run this script directly:

Terminal
Output
# No output

Structuring Scripts vs Modules

Using the if __name__ == "__main__" idiom helps you separate executable code from reusable code. This is particularly useful when you want to make your scripts both executable and importable.

Example 2: Executable and Importable Script

Consider a script named calculator.py that defines a function for adding two numbers.

calculator.py
1def add(a, b):
2 return a + b
3
4if __name__ == "__main__":
5 result = add(3, 4)
6 print(f"The sum is {result}")

You can run this script directly to see the output:

Terminal
Output
The sum is 11

The main() Function Pattern

Another common practice in Python is to define a main() function that encapsulates the executable code. This pattern enhances readability and makes your script more organized.

Example 3: Using the main() Function

Let's refactor the previous calculator.py example to use the main() function pattern.

calculator.py
1def add(a, b):
2 return a + b
3
4def main():
5 result = add(3, 4)
6 print(f"The sum is {result}")
7
8if __name__ == "__main__":
9 main()

Running this script directly:

Terminal
Output
The sum is 11

Common Mistakes and Pitfalls

  1. Incorrect Indentation: Ensure that the code inside the if __name__ == "__main__" block is properly indented.
  2. Misspelling name: Double-check for any typos in __name__. It should be exactly __name__, not _name_ or name.
  3. Forgetting to Define main(): If you use the main() function pattern, make sure to define the main() function before calling it.

Practical Example

Let's create a complete example that combines all these concepts: an executable script with reusable functions and the main() function pattern.

Example 4: Complete Script Using name and main()

Create a file named app.py.

app.py
1def greet(name):
2 return f"Hello, {name}!"
3
4def add(a, b):
5 return a + b
6
7def main():
8 name = "Alice"
9 greeting_message = greet(name)
10 print(greeting_message)
11
12 result = add(10, 20)
13 print(f"The sum is {result}")
14
15if __name__ == "__main__":
16 main()

Run the script directly:

Terminal
Output
Hello, Bob!
The sum is 40

Summary

ConceptDescription
__name__ VariableHolds the name of the current module. '__main__' when run directly.
if __name__ == "__main__"Idiom to separate executable code from reusable code.
Structuring Scripts vs ModulesUse if __name__ == "__main__" to make scripts both executable and importable.
main() Function PatternEncapsulates executable code for better organization and readability.

What's Next?

Now that you understand how to structure your Python scripts using the __name__ variable and the if __name__ == "__main__" idiom, you're ready to explore more advanced topics such as handling dates and times in Python. In the next tutorial, we will delve into the datetime module and learn how to work with dates, times, and time intervals.

Continue your journey by exploring Python Dates and Time.


PreviousPython Modules, Packages & PIPNext Python Dates and Time

Recommended Gear

Python Modules, Packages & PIPPython Dates and Time