I've seen code such as:
if __name__ == "__main__":
main()
What does main()
mean there? Is it a function of some sort?
I've seen code such as:
if __name__ == "__main__":
main()
What does main()
mean there? Is it a function of some sort?
main() is a function. However, you need to define it. If you have ever used another programming language, such as Java, C, or C++, you'd have heard of a main method. You define your own main method, then tell Python to use it immediately. It is typically just for good practice, so for example
if __name__ == "__main__":
main()
def main():
print("Hello, World")
Is the same as
print("Hello, World")
Later on in your Python career, you will learn the benefits of this script.
example1.py
print ("Always executed example1")
def main(param):
print(param)
if __name__ == "__main__":
print ("Executed example1 when invoked directly ")
main('main invoked directly')
else:
print ("Executed example1 when imported")
main('main invoked when imported')
example2.py
import example1
if __name__ == "__main__":
print ("Executed example2")
example1.main('main invoked from example2 __name__')
Output when example1.py runs:
Always executed example1
Executed example1 when invoked directly
main invoked directly
Output when example2.py runs:
Always executed example1
Executed example1 when imported
main invoked when imported
Executed example2
main invoked from example2 __name__
In simple words:
main()
is jus a function defined and if it's under under if __name__ == "__main__":
, will only get called upon when your Python file is executed as python example1.py
However, if you wish to import your Python file example1.py as a module to work with another Python file, say example2.py, the code under if __name__ == "__main__":
will not run or take any effect.