In python, the main function is the start point for any program. The main function will only run when the file is run directly, not when it is imported in another file.
Example:
def main(): print(“Python is cool!”) print(“Hello world!”)
Output:
Hello world!
In the example above, “Python is cool!” is not printed out because we did not declare the function if __name__ == “__main__”.
This function uses the __name__ variable, which is a special variable which python changes to “__main__”. When imported into another python file, the __name__ variable assumes the name of the module. Therefore, the code inside the “if __name__ == __main__” function only executed when the file is run directly and not from any imports.
Example:
def main(): print(“Python is cool!”) print(“Hello world!”) if __name__ == “__main__”: main()
Output:
Hello world! Python is cool!