How to add the code to execute the main function in Python when we run any program.
I want to execute my main() function of the following program.
This is also a little bit different than Java and C language because unlike in Java and C Python doesn’t automatically look for a function named main when the program starts.
So, what we need to do is this, I have to write if, and I’m going to type __name__, is equal to, and then inside quotes, two underscores and then main, and then two underscores. Then I’m going to call the function main.
if __name__ == '__main__':
main()
Right, so why do we need to do this?
These line of code is checking to see that when this particular Python function, right, when this file of Python code is loaded and the Python interpreter is about to run things, what’s going to happen is it’s going to look to see if this value, this property is equal to main.
Because in Python you might be executing your code as a program, but you might also be including this code as a module in another program.
And if this was executed from the terminal or the command line, then I want the main function to be called.
Now, if the code was included as a module in another program, then I wouldn’t want all my code just to start running when it was imported into the other program, because that would cause problems.
So lines 1 and 2 help distinguish between when a Python file is being included in another program, or when that Python code is being executed as its own program.
So in our case, the file is being executed as its own program and line 1 will evaluate to true, and the main function will be called.
#python #pythonprogramming #programming