Python Main Function

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

PYTHON MAIN FUNCTION DESCRIPTION?

Definition :

Python main function is a starting point of any program. When the program is
run, the python interpreter runs the code sequentially. Main function is executed
only when it is run as a Python program. It will not run the main function if it
imported as a module.

To understand this, consider the following code

def main():
print ("hello world!")
print ("Guru99")

Output : Guru99

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():
print("Hello World!")

if __name__ == "__main__":
main()

print("Guru99")

Output :
Hello World!
Guru99

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, 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, consider the following code:

#mainfunction.py

def main():
print("Hello World!")

if __name__ == "__main__":
main()

print("Guru99")
print("Value in built variable name is: ",__name__)

Output :

Hello World!
Guru99
Value in built variable name is : __main__

Now consider, code is imported as a module

import mainfunction
print("done")

output:

Guru99
Value in built variable name is : mainfunction
done

Here, is the code explanation:

Python interpreter uses the main function in two ways

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

Conclusion : 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.

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.

You might also like