Python if __name__ == ‘__main__’:main()

That may be the ugliest name for a webpage I have ever seen!

if __name__ == ‘__main__’:main()   #it basically means… hey go run the main() function

This statement is a new concept and most of the time on Python tutorials people will gloss over this and just tell you to use it and not bothering to understand it.  This can frustrate some people, so I wanted to include a description of this if statement.  It is not critical that you understand every aspect of what it does, but it will get you thinking about what it does and hopefully it will make sense one day.

It is VERY common in Python programs to see this line of code.  We have seen this before, it just looks a little funny here.  It is just a basic “if” statement.  Here is how it reads.

If variable named “__name__” is equal in value to a variable named “__main__” then run the main() function of the program.

It can be written in the following format which may look more familiar.

if __name__ == '__main__':
    main()
    print('This was run directly by Python.')
else:
    print("This was imported and then run.")

Before Python runs your program it does some things behind the scenes.  One of those things is to assign a value to the variable “__name__.”

Create a Python file named “firstMod” and enter the following and run it.

print(__name__)

It will print out the value of the variable just like the other variables we have printed before.  The output is “__main__.”   So now we know it has a value without us doing anything.  Python has assigned that on its own.

What the whole line is asking is, is this being run directly by Python or is this being imported by another program.

def main():
    print("This First Module's Main Method")

#When imported the __main__ is not the first module.
if __name__ == '__main__':
    main()
    print('This was run directly.')
else:
    print("This was imported and then run.")

Now create a second Python file named “secondMod” and paste in the following.  We are going to import the firstMod into the secondMod and see the value of __name__ changes.

import firstModule

print()
firstModule.main()

print()
print("The Second Module's Name Is: ", __name__)

When you run secondMod you can see it imports firstMod and causes the else statement to trigger, meaning __name__ is no longer equal to __main__.

If you are confused, great it means your horizons are expanding!   Most tutorials do not bother explaining this at all because it is confusing.  So… do not worry about it.  Keep pushing forwards!