Understand main function | Python
Till now we have covered how to install python and PyCharm. How to write basic Hello world program. The basic syntax for python. Now we will move ahead and dig little more into python. This is one short article for the same to understand a small concept of python. If you are familiar with java language. The execution of the program in Java starts with main method the same it is important to get familiarise with Python main function(__main__ function). We will also see its importance in this article.
See the below code:
def main(): print ("Called from main") print ("Called outside main")
If we run above code:
Only “Called outside main” prints out. See the below snippet:
The reason for not printing “Called from main” is that we defined the function but we did not declare the call function if __name__ == “__main__”.
- Python will execute all the code from a source file when the interpreter reads the source file
- On Running the source file, it sets a special variable (__name__) to have a value ("__main__").
- It will then read the "if" statement and checks whether __name__ does equal to __main__.
- In Python "if__name__== "__main__" allows you to run the Python files either as reusable modules or standalone programs.
It is important that after defining the main function, you call the code by if__name__== "__main__" and then run the code, only then you will get the output “Called from main!” in the programming console as shown below.
Now it is gets printed. So now onwards don’t forget to invoke the main function 🙂
This is one of the shortest articles we will probably have in this Python Tutorial series but I kept it separate as it was important one.
That's all for this topic. If you guys have any suggestions or queries, feel free to drop a comment. We would be happy to add that in our post. You can also contribute your articles by creating contributor account here.
Happy Learning 🙂
About the Author
Comments and QueriesIf you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code class="java"> String foo = "bar"; </code></pre>For more information on supported HTML tags in disqus comment, click here.