Python’s Mysterious ‘if __name__ == “__main__”’ Explained
While reading a Python program you might find the expression if __name__ == ‘__main__’.
Let’s have a look at what it means and why you should know about it.
The condition if __name__ == ‘__main__’ is used in a Python program to execute the code inside the if statement only when the program is executed directly by the Python interpreter. When the code in the file is imported as a module the code inside the if statement is not executed.
It might not be very clear why this is done and with this tutorial, the reason will become clear.
Here we go!
What is __main__ in Python?
The word __name__ in Python represents a special variable.
There are many special variables in Python that start and end with double underscores. To make it short they are referred to as dunder (from Double Underscores). So __name__ is pronounced “dunder name”.