Python Essential Interview Questions

One of the most essential Python interview questions is explaining to interviewer the reason for having __main__() function in Python

if __name__ == "__main__":

Python does not have a well defined entry point like Java or C++, it simply executes a source file line by line. In Python, execution of code does not have to start at main. The first line of executable code is executed first. Every module has a name and statements in a module can find out the name of its module. This is partuculary useful in one particular situation, as mentioned before, when a module is imported for the first time, the main block in that module is executed. What if we want to execute the block only if the program was used by itself and not when it was imported from another module? This can be achieved using the name attribute of the module

No comments:

Post a Comment