Member-only story
Concept behind `if __name__ == “__main__”` in Python

Obviously, there is some confusion about this block. Sometimes this question has arisen that why this block is needed? It’s unnecessary…!! Someone like me who has strong beliefs that this block makes python code more beautiful.
Umm! Wait! I think that’s true in one scene because this block makes your py file looks prettier.
However, this block of code has definitely a meaning and a valid use-case. When you want not to use some chunk of your code from one py file to another py file and happy to see when the main file is run, then, in this case, this block of code plays a good role.
It will be more clear after seeing an example. Let we have 2 py file named, a.py
and b.py
and some function to execute.
a.py
def add(x, y):
return x + yprint( add(10, 10) )if __name__ == '__main__':
print( add(4, 1) )
b.py
from a import addprint( add(100, 1) )
Now run both of this file. Just notice when you run a.py
20
and 5
is visible in your console. But when you import add()
function from a.py
file to b.py
file and try to run b.py
..what happen? console shows only 20 and 100+1
I mean 101
result. But why…