Main Function in Python

Overview

In Python, the main function serves as the entry point for a script. It is a common practice to define a main function and call it within the if __name__ == '__main__': block. This ensures that the code is executed only when the script is run directly, and not when it is imported as a module. This practice provides a clear structure to the script and allows for better control, especially in larger applications.

Basic Structure

A Python script can be as simple as a sequence of statements in a file. However, introducing a main function adds structure and clarity. The basic form involves creating a controlling function and calling it. Below is an example of a simple script with a main function:

[Listing 11.1 File script1.py](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-11/12)

def main():                              #A
    print("this is our first test script file")
main()                                  #B
#A Controlling function main
#B Calls main

In this script, main is the controlling—and only—function. It is first defined and then called. While this structure might not seem necessary for small programs, it is beneficial for larger applications, providing more options and control.

Conditional Execution

To ensure that the main function is only executed when the script is run directly, and not when it is imported as a module, a conditional test is used:

if __name__ == '__main__':
    main()
else:   #A
    # module-specific initialization code if any
#A else section is optional

When a file with this structure is executed as a script, the variable __name__ is set to "__main__", triggering the call to the main function. If the script is imported as a module, its name will be its filename, and the code within the if block will not be executed. The optional else block can be used for module-specific initialization code, which will only run if the file is imported as a module.

FAQ (Frequently asked questions)

What is the purpose of the main function in a Python script?

What does the main function do in the script1.py example?

How is the main function called in the script1.py example?

What is the purpose of the comment '#A Controlling function main' in the script1.py example?

What does the comment '#B Calls main' signify in the script1.py example?