Why use def main()?

Wizzard picture Wizzard · Oct 28, 2010 · Viewed 709.7k times · Source

I've seen some code samples and tutorials that use

def main():
    # my code here

if __name__ == "__main__":
    main()

But why? Is there any reason not do define your functions at the top of the file, then just write code under it? ie

def my_function()
    # my code here

def my_function_two()
    # my code here

# some code
# call function
# print(something)

I just wonder if there is any rhyme to the main?

Answer

Ignacio Vazquez-Abrams picture Ignacio Vazquez-Abrams · Oct 28, 2010

Without the main sentinel, the code would be executed even if the script were imported as a module.