What does if __name__ == “__main__” mean?
We all have come across if __name__ == ‘__main __’: in python codes found online. Ever wondered what it means…
Whenever the Python interpreter reads the source file, it sets a special variable “__name__” to “__main__”.
Whenever it reads an imported file, it sets the variable “__name__” to the name of the file.
Now that we have understood the meaning of the variable “__name__”. Let’s see what if __name__ == ‘__main__’: means and its significance.
As we can see File_One.py has produced the output we expected but File_Two.py did not.
File_Two.py should have produced this
But, instead, it has produced the output of File_One.py and File_Two.py This has happened because Python executes all the code present in both the source file and the imported file.
To avoid it we are using the __name__ variable.
I hope this explanation provides a clear understanding of why we use if __name__ == ‘__main__’: