Python main function Explained

The starting function


Unlike C/C++, which starts with the main function, python programs execute in order from start to finish.

Let's summarize the role of the main function in python:

It makes the module (function) can be executed (debug) on its own, which is equivalent to constructing the entrance to call other functions, which is similar to the main function in C/C++.

Related course: Complete Python Programming Course & Exercises

How to Write a Python main Function?

Here's the actual main function example (assuming this file is test.py).

#test.py
print('Hello World!')

def aaa():
    print('this message is from aaa function')

def main():
    print('this message is from main function')

if __name__ == '__main__':
    main()
    print('now __name__ is %s' %__name__)

Execute python test.py Output.

Hello World!
this message is from main function
now __name__ is __main__

Here we see that the aaa function we defined is not executed, but the contents of the main function are executed, indicating that if _name__ == __main__': this judgment statement is passed, executing the main() of the judgment condition;

python main function

When the Python script is imported as a module

On the other hand: you can use functions from other .py files with the import command,

We import the modules (functions) from test.py into call.py, noting that test.py and call.py are in the same folder;

#call.py
from test import aaaaaa()
print ('now __name__ is %s' %__name__)

Execute python call.py Output.

Hello World!
this message is from aaa function
now __name__ is __main__

So when we write our own .py file and want to test the functions in it, just construct a main function entry and you can call the test function you wrote~.

Add: test2.py

print('Hello World!')
def aaa():
    print('this message is from aaa function')

def main():
print('this message is from main function')
main()
aaa()

Output.

Hello World!
this message is from main function
this message is from aaa function