Home >Backend Development >Python Tutorial >What does if __name__ =__main__ do in Python?
You might have seen this line of code if __name__=="__main__": a lot in Python scripts, without knowing what is it's actual purpose. Don't worry because in this short blog we will be discussing this
When you directly run a program or script, Python automatically assigns "main" to the special name variable. This is basically done to indicate that the file is the "main" script here and is being run directly instead of being imported into another.
To understand this, create a new Python script, let's say name it "example.py" and write:
print("Name of Script: ", __name__)
Run this and you will see the output Name of Script: __main__. This is simply because the file is being run directly.
Now, create another python script file and import the example.py into this fie. Run it and you will see a different result saying Name of Script: example. This is simply because now instead of running it directly, we are importing the script and running it indirectly. Thus, Python is now showing the actual name of the file.
Let's make some changes in our example file, so that we can understand it even better.
def s_name(): print("Name of Script: ", __name__) s_name() def greet(): print("Hello! How are you doing?") if __name__=="__main__": greet()
Now if you run this directly everything would be perfectly executed but if you run the other file where you are importing the example.py script, you will notice that the greet function call was not executed. Why is that?
This is because of the if conditional. What the conditional does is that it checks if the file is being run directly or not. If it is being run directly, main would be assigned to the special variable name which will make this condition true and everything inside the condition will run as usual.
But on the other hand, if you are importing it on another file and running it from there indirectly, then the condition statement would not be true and anything that was placed inside the conditional will not get executed.
This is the significance of this conditional statement. It prevents the Python interpreter from automatically running unnecessary lines of code when we import a script as a module.
However, we can call these functions even when we are importing a script as a module. For example:
import example example.greet()
In this way we can perfectly call any functions from the imported module even when the conditional is not satisfied.
The above is the detailed content of What does if __name__ =__main__ do in Python?. For more information, please follow other related articles on the PHP Chinese website!