🐍 if __name__=='__main': is used to find if a program is run directly or is being called from another program. if __name__=='__main' returns true if it is run directly. Under if __name__=='__main': you can put the lines of code you want to execute if a program is run directly.
Here is an example to understand the usage. We are creating two files. One will have functions. Other will call these functions. We will then run file one directly and then run file two and call functions from file one in file two.
def func():
print('func() in one.py')
print('in one.py')
if __name__ == "__main__":
print('one.py is being run directly')
else:
print('one.py has been imported')
import one
print('in two.py')
one.func()
if __name__ == "__main__":
print('two.py is being run directly')
else:
print('two.py has been imported')
Here is an example to understand the usage. We are creating two files. One will have functions. Other will call these functions. We will then run file one directly and then run file two and call functions from file one in file two.
one.py
#RUN ON COMMAND PROMPT: python one.pydef func():
print('func() in one.py')
print('in one.py')
if __name__ == "__main__":
print('one.py is being run directly')
else:
print('one.py has been imported')
two.py
#RUN ON COMMAND PROMPT: python two.pyimport one
print('in two.py')
one.func()
if __name__ == "__main__":
print('two.py is being run directly')
else:
print('two.py has been imported')
Save and run both files one after the other on Command Prompt.
Comments
Post a Comment