What exactly is __name__ Special Python Variable? Explained in simple words

Опубликовано: 11 June 2026
на канале: Example Program
341
8

In this video, we will talk about a special built-in variable called _name_ in the Python programming language. We will see what it is, what it contains, and how we can use it in our programs.

_name_ is a special built-in variable that is available in Python, which helps us understand how a Python script is being used. It allows us to determine whether a Python script is being run directly as a standalone program or whether it is being imported as a module by another script. When a Python script or file containing Python code is executed, the Python interpreter sets this variable with specific values. If the Python file is run directly as a standalone program, the _name_ variable gets the value _main__. If the Python file is imported as a module by another script, the __name_ variable gets the name of the file or module, which in this case, would be hello.

To explain this, I have created two files in the code folder: hello.py and program.py. We will start with both files being empty and add the necessary code step by step.

In this video, you will learn what happens when a Python script is executed directly versus being imported as a module. We will create examples in hello.py and program.py to demonstrate the usage of the _name_ variable. We will also see how placing the code inside functions can affect the behavior of the _name_ variable. Additionally, you will discover how to control what part of the code is executed when the script is run as a standalone program versus when it is imported as a module.

We will explore how placing code inside functions can impact the behavior of the script and how you can make use of this special variable to control the execution flow. By the end of the video, you'll understand how to use the _name_ variable effectively in your Python scripts. This is an essential concept that helps in writing modular and testable Python code.

The video starts with an introduction to the _name_ variable and how it behaves when the script is run directly. Then, we demonstrate the effect of importing modules on the _name_ variable. We go further to show how using functions affects the behavior of the variable and conclude with practical use cases and examples. You will also learn when and how to use the _name_ variable to control execution flow in Python programs.

our Social Media Pages
  / exampleprogram  
  / exampleprogram  
  / example_program  

Our Website
https://www.ExampleProgram.com

#ExampleProgram