Usage of if __name__ == ‘__main__’ in Python
Hello friends, In this segment, we are going to discussĀ if_name_== ‘_main_’. In this segment, I will tell you how to use if_name_== ‘_main_’ in your file and what is the need to use. So our first question is what is the need of if_name_== ‘_main_’? and the answer is if you want to use a file’s variables and functions in another file then you simply import the previous file into the current file and use the function or variable but the problem is when you run the current file then it gives the output with first file’s program execution.
It means if you want to use only some functions of the previous file in the current file it also produces the output of the previous file. So for solving this type of problem, you should use if_name_== ‘_main_’. Let us understand it by an example.
Here you can see a screenshot above this is my first file and my second file is below.
So as you have seen when I have run my second file it is producing my first file’s output also. For removing this type of problem now I will use if_name_== ‘_main_’.
How to use if_name_== ‘_main_’
Our second is how to use if_name_== ‘_main_’. So the answer is in your previous file (the file from where you are importing variables and functions) you have to use if_name_== ‘_main_’. In your IDE you have to type main and then hit enter it will automatically take if_name_== ‘_main_’. Now see the screenshot below.
Now if we write our other file and want to use the previous file’s some function then it will execute only the previous files those function which we want to use in our current file. Now take a look at code below.
from tut1 import mohit2 mohit2(2,5)
And when we run this code this will produce its output.
Output:
7 Process finished with exit code 0
Also read:
Leave a Reply