def main() Example 1
Here, we got two pieces of print- one is defined within the main function that is “Hello World!” and the other is independent, which is “Guru99”. When you run the function def main ():
Only “Guru99” prints out and not the code “Hello World!”
It is because we did not declare the call function “if__name__== “main”. 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 “hello world!” in the programming console. Consider the following code
def main() Example 2
Here is the explanation,
When Python interpreter reads a source file, it will execute all the code found in it. When Python runs the “source file” as the main program, it sets the special variable (name) to have a value (“main”). When you execute the main function in python, 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.
The name variable and Python Module
To understand the importance of name variable in Python main function method, consider the following code:
Now consider, code is imported as a module
Here, is the code explanation: direct run:
name=main if statement == True, and the script in _main_will be executed
import as a module
name= module’s filename if statement == false, and the script in main will not be executed
When the code is executed, it will check for the module name with “if.” This mechanism ensures, the main function is executed only as direct run not when imported as a module. Above examples are Python 3 codes, if you want to use Python 2, please consider following code In Python 3, you do not need to use if__name. Following code also works Note: Make sure that after defining the main function, you leave some indent and not declare the code right below the def main(): function otherwise, it will give indent error.