Home » Learn Python » Functions » Python Main Functions

Python Main Functions

It’s common for functions to call other functions, in programming generally.

This can make it hard to see where the “entry point” of a program is. Where does the program actually start executing?

For this reason, computer programs often have a function called main, which gets called before any other function. Main itself then calls other functions.

In Python there’s nothing special about functions called main, but it’s common to define one as the entry point for your program.

def greeting():
    print("Hello there!")

# This main() just calls greeting twice.
def main():
    greeting()
    greeting()

# We need to actually call main to start the program.
main()
Hello there!
Hello there!

Conditionally Executing Main

A problem arises in Python from the fact that you can load files as modules in other files, enabling you to use a file’s functions in another file.

When a module is loaded, its code gets executed. This means that if it contains a main, that will also get executed. But you only want main to be called if you’re actually running the file as a program, not loading it as a module.

We can avoid running main when the file is a module using the __name__ variable. When the file is run as a program, this variable will contain the text “__main__“. When the file is loaded as a module, it will contain the name of the module instead.

def greeting():
    print("Hello there!")

# This main() just calls greeting twice.
def main():
    greeting()
    greeting()

# Only run main if this file is run
# directly from the commmand line.
if __name__ == "__main__":
    main()
Hello there!
Hello there!

Leave a Reply

Blog at WordPress.com.

%d